I have a Table like this
SNo Block SAP SAG BAP BAG DEP DEG
1 600403 1 3 5 4
2 600405 1 3 1 3 1 1
3 600407 3 1 2 4
4 600409 3 1
5 600410 1 3 2 5 1 3
6 600413 1 4 1 3
I want to NULL the Cells of SAP and SAG where SAP = 1 and SAG = 3, and null the cells of BAP and BAG where BAP = 1 and BAG = 3 and like wise for DEP and DEG, i am expecting result like this below
SNo Block SAP SAG BAP BAG DEP DEG
1 600403 5 4
2 600405 1 1
3 600407 3 1 2 4
4 600409 3 1
5 600410 2 5
6 600413 1 4
Some how after googling, I wrote a code for this, and the code runs successfully without any error but only the SAP Column gets NULLed and the SAG column was not NULLed (the second Query for SAG docmd doesn't work) !
Below is my VBA, Sorry I am new to Access VBA !
Private Sub VbaModule()
Dim db As DAO.Database
Dim rs As Recordset
Dim sSQL As String
Dim sSQL1 As String
Set db = CurrentDb()
Set rs = db.OpenRecordset("T05_Pr2_Null_Not_In_Rem")
sSQL = "UPDATE T05_Pr2_Null_Not_In_Rem SET SAP = NULL " & _
" WHERE (SAP = 1 AND SAG = 3)"
DoCmd.RunSQL sSQL
sSQL = "UPDATE T05_Pr2_Null_Not_In_Rem SET SAG = NULL " & _
" WHERE (SAP = 1 AND SAG = 3)"
DoCmd.RunSQL sSQL
rs.Close
Set rs = Nothing
db.Close
End Sub
Any Suggestion ?
Dim strSQL As String
strSQL = "UPDATE T05_Pr2_Null_Not_In_Rem " & _
"SET " & _
" SAP = NULL, " &
" SAG = NULL " & _
"WHERE SAP = 1 AND SAG = 3;"
CurrentDb.Execute strSQL, dbFailOnError
strSQL = "UPDATE T05_Pr2_Null_Not_In_Rem " & _
"SET " & _
" BAP = NULL, " &
" BAG = NULL " & _
"WHERE BAP = 1 AND BAG = 3;"
CurrentDb.Execute strSQL, dbFailOnError
strSQL = "UPDATE T05_Pr2_Null_Not_In_Rem " & _
"SET " & _
" DEP = NULL, " &
" DEG = NULL " & _
"WHERE DEP = 1 AND DEG = 3;"
CurrentDb.Execute strSQL, dbFailOnError
Related
I have this table and this code
CAMPO10. CAMPO12
1 01012018
2 01012018
1 05012018
2 -
1 10012018
2 10012018
strSQL = "SELECT * from MESERIFERIMENTO;"
rs.Open strSQL, cnn, 3, 3
Do While Not rs.EOF
If rs("Campo10") = 1 Then
campo4 = rs("Campo10")
campo5 = rs("Campo12")
End If
If rs("Campo10") = "2" And IsNull(rs.Fields("Campo12").Value) Then
MsgBox "Has nulls"
strSQL = "Update MESERIFERIMENTO SET [Campo12] ='" & campo5 & "' ;"
DoCmd.RunSQL strSQL
End If
rs.MoveNext
Loop
rs.Close
Thank you
Like this:
strSQL = "SELECT * from MESERIFERIMENTO;"
rs.Open strSQL, cnn, 3, 3
Do While Not rs.EOF
If rs("Campo10").Value = 1 Then
campo5 = rs("Campo12")
End If
If rs("Campo10").Value = 2 And IsNull(rs.Fields("Campo12").Value) Then
MsgBox "Has nulls"
rs("Campo12").Value = campo5
rs.Update
End If
rs.MoveNext
Loop
rs.Close
You could use the Nz function in your query to convert nulls to 0 if 0 is not excpected.
strSQL = "SELECT Campo10, Nz(Campo12,0) from MESERIFERIMENTO;"
rs.Open strSQL, cnn, 3, 3
Do While Not rs.EOF
If rs("Campo10") = 1 Then
campo4 = rs("Campo10")
campo5 = rs("Campo12")
End If
If rs("Campo10") = "2" And rs("Campo12")=0 Then
MsgBox "Has nulls"
strSQL = "Update MESERIFERIMENTO SET [Campo12] ='" & campo5 & "' ;"
DoCmd.RunSQL strSQL
End If
rs.MoveNext
Loop
rs.Close
I have a query table and transfer to excel. I loop from cell range to re-query into database and it works fine but it really take so much time since i used below code.. The code need to query and do recordset every time satified IF condition in each single cell. Is there other way that this code will execute in database server and once complete then, only do a recordset?
'Set Connection
Set Cn = CreateObject("ADODB.Connection")
Cn.Open "Driver={MySQL ODBC 5.3 ANSI Driver};Server=" & _
Server_Name & ";Port=" & Port & ";Database=" & Database_Name & _
";Uid=" & User_ID & ";Pwd=" & Password & ";"
'Set Recordset
Set rs = CreateObject("ADODB.Recordset")
rs.CursorLocation = 3
rs.Open SQLQuery, Cn, adOpenStatic
myArray = rs.GetRows()
kolumner = UBound(myArray, 1) 'Count number of Columns
rader = UBound(myArray, 2) 'count number of rows
For K = 0 To kolumner ' Using For loop data are displayed
Range("A5").Offset(0, K).Value = rs.Fields(K).Name 'Field is the header
of each column and not included in Array. Field(0) means header of first
column.
For R = 0 To rader
Range("A5").Offset(R + 1, K).Value = myArray(K, R)
Next
Next
set rows = 0 to rader
Range("L5").Value = "Debug Note" 'insert Name of Column
For R = 6 To 1100
Datevalue = Sheets("Sheet1").Range("I" & R)
Dateexcel = FORMAT(Datevalue, "yyyy-MM-dd HH:mm:ss")
SQLQuery2 = "SELECT * FROM Mfg.databasemodels_note " & _
"where typeId = " & Sheets("Sheet1").Range("B" & R) & " AND
date > " & "'" & Dateexcel & "'" & " order by date asc
limit 1;"
Set rs2 = CreateObject("ADODB.Recordset")
rs2.CursorLocation = 3 'client
rs2.Open SQLQuery2, Cn, adOpenStatic
myArray2 = rs2.GetRows()
If Not (rs2.BOF And rs2.EOF) And (Range("J" & R).Value = "failed" Or
Range("J" & R).Value = "invalid") Then
Range("L" & R).Value = myArray2(3, 0)
Else
End If
On Error Resume Next
rs2.Close
Set rs2 = Nothing
Next
I'm new to vb.net and I'm creating thesis project in our school. I want to fetch data from my excel file where cells was merge and it keeps on popping conversion from type 'Range' to type 'String' is not valid. Here's my code that I copied and credits for them:
Try
con.Open()
workbook = app.Workbooks.Open(fileOpener.SelectedPath + "\ahrmt.xlsx")
worksheet = workbook.Worksheets("Sheet1")
curbook = 0
Me.Text = String.Format("{0:F0}%", ((curbook / books) * 100)) + " of records has been imported."
Dim cmd As New MySqlCommand
Dim maxrow As Integer = 9
Dim noRecs, AYear As Integer
Dim semester, course As String
Me.lblWait.Visible = True
'=====================================
Dim str As String
str = worksheet.Range("A6").Text
If str.Contains("FIRST SEMESTER") = True Then
semester = "First Semester"
Else
semester = "Second Semester"
End If
Dim exAY = Regex.Replace(worksheet.Cells(6, 1), "\D", "")
AYear = exAY
Dim AcadY As New System.Text.StringBuilder()
For i As Integer = 0 To exAY.Length - 1
AcadY.Append(exAY(i))
If i Mod 4 = 3 AndAlso i > 0 AndAlso i < exAY.Length - 1 Then
AcadY.Append(" - ")
End If
Next
course = "Associate in Hotel and Restaurant Management Technology"
'=======================================
'--------to get the total rows
For x As Integer = 9 To worksheet.Rows.Count
If worksheet.Cells(x, 2).Value = Nothing Then
Exit For
Else
maxrow += 1
End If
Next
'----------for inserting records
For i As Integer = 9 To worksheet.Rows.Count
If worksheet.Cells(i, 2).Value = Nothing Then
Exit For
Else
Me.ProgressBar1.Visible = True
Me.ProgressBar1.Value += 1
Me.ProgressBar1.Maximum = maxrow - 9
Me.lblImport.Text = String.Format("{0:F0}%", ((ProgressBar1.Value / ProgressBar1.Maximum) * 100))
cmd.Connection = con
cmd.CommandText = "INSERT INTO tblsif(IDNo, Status, FName, MName, LName, Gender, YearLevel, Semester, AcadYear, PresCourse) " & _
"VALUES('" & worksheet.Cells(i, 2).Value & "','" & enrolledStat & "','" & worksheet.Cells(i, 5).Value & "','" & worksheet.Cells(i, 6).Value & "'," & _
"'" & worksheet.Cells(i, 4).Value & "','" & worksheet.Cells(i, 10).Value & "','" & worksheet.Cells(i, 1).Value & "','" & semester & "','" & AcadY & "','" & course.ToString & "')"
cmd.ExecuteNonQuery()
noRecs += 1
Me.lblTotalRec.Text = "Importing " + noRecs.ToString + " records from AHRMT Course."
End If
Next
'workbook.Save()
workbook.Close()
app.Quit()
Catch ex As Exception
MsgBox(ex.Message)
End Try
Me.ProgressBar1.Value = 0
Me.ProgressBar1.Visible = False
Me.lblTotalRec.Text = Nothing
Me.lblImport.Text = Nothing
con.Dispose()
con.Close()
curbook = 1
Me.Text = String.Format("{0:F0}%", ((curbook / books) * 100)) + " of records has been imported."
Hope you can help me.
I have a query that generates a table like this:
Row 1 - ID 1 Peter Parker Task 1 $50
Row 2 - ID 1 Peter Parker Task 2 $55
Row 3 - ID 1 Peter Parker Task 3 $60
Row 4 - ID 2 Mary Jane Task 1 $45
Row 5...
I want to be able to send one email to each person with a list of the tasks and amounts, and the total amount:
Peter Parker
Task 1 $50
Task 2 $55
Task 3 $60
Total $165
I've got a module that sends email, but it requires a single recipient per row. I'm thinking I need another loop, but I'm lost as how to do this.
Here's the code I'm using now:
Sub SendMessages(Optional AttachmentPath)
Dim MyDB As Database
Dim MyRS As Recordset
Dim objOutlook As Outlook.Application
Dim objOutlookMsg As Outlook.MailItem
Dim objOutlookRecip As Outlook.Recipient
Dim objOutlookAttach As Outlook.Attachments
Dim TheAddress As String
Set MyDB = CurrentDb
Set MyRS = MyDB.OpenRecordset("qry_TeacherPayment - Round 2")
MyRS.MoveFirst
' Create the Outlook session.
Set objOutlook = CreateObject("Outlook.Application")
Do Until MyRS.EOF
'Set loop variables
Dim currentRecord As Integer
Dim oldRecord As Integer
Dim totalAmt As Double
currentRecord = MyRS![ID]
totalAmt = 0
If (currentRecord = MyRS![ID]) Then
' Create the e-mail message.
Set objOutlookMsg = objOutlook.CreateItem(olMailItem)
oldRecord = currentRecord
TheAddress = MyRS![WorkEmail]
With objOutlookMsg
' Add the To recipients to the e-mail message.
Set objOutlookRecip = .Recipients.Add("TheAddress")
objOutlookRecip.Type = olTo
' Set the from address.
objOutlookMsg.SentOnBehalfOfName = "email"
' Set the Subject, the Body, and the Importance of the e-mail message.
.Subject = "Subject"
objOutlookMsg.BodyFormat = olFormatHTML
body text
.HTMLBody = .HTMLBody & "</table></body></html>"
.Importance = olImportanceNormal 'Normal importance
' Resolve the name of each Recipient.
For Each objOutlookRecip In .Recipients
objOutlookRecip.Resolve
If Not objOutlookRecip.Resolve Then
objOutlookMsg.Display
End If
Next
.Send
End With
End If
MyRS.MoveNext
Loop
Set objOutlookMsg = Nothing
Set objOutlook = Nothing
DoCmd.SetWarnings True
End Sub
Here is my final code that works a treat. A huge thanks to maxhugen for putting me on the right path!!
Cheers!
Jason
Sub SendNewPaymentEmail(Optional AttachmentPath)
Dim MyDB As Database
Dim MyRS As Recordset
Dim LastTeacherID As Integer
Dim EmailBody As String
Dim TotalAmount As Double
Dim TheAddress As String
Dim TeacherFirstName As String
Dim FinalTeacherID As Integer
Set MyDB = CurrentDb
Set MyRS = MyDB.OpenRecordset("qry_TeacherPayment - Round 2")
MyRS.MoveFirst
LastTeacherID = MyRS![ID]
Do Until MyRS.EOF
If MyRS![ID] = LastTeacherID Then
TheAddress = MyRS![WorkEmail]
TeacherFirstName = MyRS![FirstName]
FinalTeacherID = MyRS![TeacherID]
EmailBody = EmailBody & "<tr><td>" & MyRS![Subject] & " Year " & MyRS![Year] & "</td><td>" & MyRS![TaskName] & "</td><td>$" & MyRS![Teacher Payment] & "</td></tr>"
TotalAmount = TotalAmount + Nz(MyRS![Teacher Payment], 0)
DoCmd.SetWarnings False
DoCmd.RunSQL "Update [tbl_Judging Standards Project round 2] SET [PaymentEmailSent] = -1 WHERE [TeacherID] = " & MyRS![ID] & " AND [TaskIDTRIM] LIKE '" & MyRS![TaskIDTRIM] & "'"
DoCmd.RunSQL "Update [tbl_Judging Standards Project round 2] SET [PaymentEmailSentDate] = Now() WHERE [TeacherID] = " & MyRS![ID] & " AND [TaskIDTRIM] LIKE '" & MyRS![TaskIDTRIM] & "'"
DoCmd.SetWarnings True
Else
Call CreateEmail(EmailBody, TotalAmount, TeacherFirstName)
DoCmd.SetWarnings False
DoCmd.RunSQL "INSERT INTO [tbl_Payments]([TeacherID],[PaymentType],[Amount],[Description],[PaymentFormSent],[PaymentFormSentDate]) VALUES(" & FinalTeacherID & ", 'Individual Payment'," & TotalAmount & ",'Judging Standards Project Phases 2 and 3 - Payment for work samples - Round 2', -1, NOW())"
DoCmd.SetWarnings True
'reset variables
EmailBody = ""
TotalAmount = 0
'start again
TheAddress = MyRS![WorkEmail]
TeacherFirstName = MyRS![FirstName]
LastTeacherID = MyRS![ID]
FinalTeacherID = MyRS![TeacherID]
EmailBody = EmailBody & "<tr><td>" & MyRS![Subject] & " Year " & MyRS![Year] & "</td><td>" & MyRS![TaskName] & "</td><td>$" & MyRS![Teacher Payment] & "</td></tr>"
TotalAmount = TotalAmount + Nz(MyRS![Teacher Payment], 0)
DoCmd.SetWarnings False
DoCmd.RunSQL "Update [tbl_Judging Standards Project round 2] SET [PaymentEmailSent] = -1 WHERE [TeacherID] = " & MyRS![ID] & " AND [TaskIDTRIM] LIKE '" & MyRS![TaskIDTRIM] & "'"
DoCmd.RunSQL "Update [tbl_Judging Standards Project round 2] SET [PaymentEmailSentDate] = Now() WHERE [TeacherID] = " & MyRS![ID] & " AND [TaskIDTRIM] LIKE '" & MyRS![TaskIDTRIM] & "'"
DoCmd.SetWarnings True
End If
MyRS.MoveNext
If (MyRS.EOF) Then
Call CreateEmail(EmailBody, TotalAmount, TeacherFirstName)
DoCmd.SetWarnings False
DoCmd.RunSQL "INSERT INTO [tbl_Payments]([TeacherID],[PaymentType],[Amount],[Description],[PaymentFormSent],[PaymentFormSentDate]) VALUES(" & FinalTeacherID & ", 'Individual Payment'," & TotalAmount & ",'Judging Standards Project Phases 2 and 3 - Payment for work samples - Round 2', -1, NOW())"
DoCmd.SetWarnings True
End If
Loop
End Sub
Assuming MyRS is returning fields something like PersonID, TaskID, TaskAmt, you need to loop through MyRS and add the Task and Amt to a string variable (eg 'strBody') UNTIL the PersonID changes - at which point you prepare and send the email using objOutlookMsg.
Set MyRS = ...
LastPersonID=MyRS!PersonID
Do Until MyRS.EOF
If MyRS!PersonID=LastPersonID Then
' concatenate to strBody
strBody = strBody & TaskID & " " & TaskAmt
' add Amt to Person's Total
decTotal = decTotal + nz(TaskAmt,0)
Else
' add the Total
strBody = strBody & "Total: " & decTotal
' send email using another function, or GoTo a named line,
' using LastPersonID and strBody
GoTo send_email
' reset the variables
strBody = ""
decTotal = 0
' concatenate to strBody
strBody = strBody & TaskID & " " & TaskAmt & "<br/>"
' add Amt to Person's Total
decTotal = decTotal + nz(TaskAmt,0)
End If
MyRS.MoveNext
Loop
Using VB 6 and Access 2003
I want to copy a table from one database to other database.
Database1
Table1
Table2
Database2
Table3
Above, I want to copy the Table3 to Database-1
Expected Output
Table1
Table2
Table3
How to write a code?
Need VB6 Code Help.
Using ADOX to copy the structure of the data would probably be the easiest way.
Dim sourceCat As New ADOX.Catalog
Dim targetCat As New ADOX.Catalog
Set sourceCat.ActiveConnection = connSource
targetCat.ActiveConnection = connTarget
Dim sourceTable As ADOX.Table
Set sourceTable = sourceCat.Tables("TableName")
Dim newTable As New ADOX.Table
Set newTable.ParentCatalog = targetCat
newTable.Name = sourceTable.Name
Dim sourceCol As ADOX.Column
Dim newCol As ADOX.Column
For Each sourceCol In sourceTable.Columns
Set newCol = New ADOX.Column
newCol.Name = sourceCol.Name
newCol.Type = sourceCol.Type
newCol.DefinedSize = sourceCol.DefinedSize
newCol.ParentCatalog = targetCat
newTable.Columns.Append newCol
Next sourceCol
targetCat.Tables.Append newTable
This is a fairly basic example, it ignores all indexes
and column properties (such as autoincrement).
A much more complete example can be found here.
Be aware that you cannot be sure you have extracted all of a table's schema even when using both ADO (which you need for CHECK constraints, WITH COMPRESSION, etc) and ACEDAO (which you need for complex data types, etc).
Here's an example of such a table:
Sub CantGetCheck()
On Error Resume Next
Kill Environ$("temp") & "\DropMe.mdb"
On Error GoTo 0
Dim cat
Set cat = CreateObject("ADOX.Catalog")
With cat
.Create _
"Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=" & _
Environ$("temp") & "\DropMe.mdb"
With .ActiveConnection
Dim Sql As String
Sql = _
"CREATE TABLE Test " & _
"(" & _
" data_col INTEGER NOT NULL, " & _
" CONSTRAINT data_col__be_positive " & _
" CHECK (data_col >= 0), " & _
" CONSTRAINT data_col__values " & _
" CHECK ( " & _
" data_col = 0 OR data_col = 1 OR data_col = 2 " & _
" OR data_col = 3 OR data_col = 4 OR data_col = 5 " & _
" OR data_col = 6 OR data_col = 7 OR data_col = 8 " & _
" OR data_col = 9 OR data_col = 10 OR data_col = 11 " & _
" OR data_col = 12 OR data_col = 13 OR data_col = 14 " & _
" OR data_col = 15 OR data_col = 16 OR data_col = 17 " & _
" OR data_col = 18 OR data_col = 19 OR data_col = 20 " & _
" ) " & _
");"
.Execute Sql
Dim rs
' 5 = adSchemaCheckConstraints
Set rs = .OpenSchema(5)
MsgBox rs.GetString
End With
Set .ActiveConnection = Nothing
End With
End Sub
The output shows that while the definition for the constraint named data_col__be_positive can indeed be extracted, the data_col__values definition cannot (because it exceeds 255 characters).
So really the solution is to always retain the code you used to create and subsequently alter the table. For me, using SQL DDL scripts for the purpose make a lot of sense (I do not need the few features that are not creatable via DDL).