Because I didn't find a proper solution, I developed an own code to convert an excel range into an html table. The result is a string and can be used within a mail for example.
The following code considers: cell dimension, font-family, -style, -size and alignment, border-style and -color (top, right, bottom, left) and interior-color
Function convertRangeToHtml(rng As Range) As String
Dim r As Range
Dim c As Range
Dim strHtml As String
strHtml = "<table style=" & Chr(34) & "border-collapse: collapse;" & Chr(34) & " > " & vbNewLine & "<tbody>"
For Each r In rng.Rows
strHtml = strHtml & vbTab & "<tr>" & vbNewLine
For Each c In r.Columns
strHtml = strHtml & vbTab & vbTab & "<td " & getCellDimension(c) & " style=" & Chr(34) & getFontStyle(c) & " " & getBorder(c) & " " & getInteriorColor(c) & Chr(34) & ">" & Trim(c.Text) & "</td>" & vbNewLine
Next c
strHtml = strHtml & vbTab & "</tr>" & vbNewLine
Next r
strHtml = strHtml & "</table>" & vbNewLine & "</tbody>"
Debug.Print strHtml
convertRangeToHtml = strHtml
End Function
Function getInteriorColor(r As Range) As String
getInteriorColor = "background-color: rgb(" & color2rgb(r.DisplayFormat.Interior.Color) & "); "
End Function
Function getBorder(r As Range) As String
Dim varBorderSytle As Variant
varBorderSytle = "border-style: "
Dim varBorderWidth As Variant
varBorderWidth = "border-width: "
Dim varBorderColor As Variant
varBorderColor = "border-color: "
For Each b In Array(8, 10, 9, 7)
Select Case r.Borders(b).LineStyle
Case -4115
varBorderSytle = varBorderSytle & "dashed "
Case -4142
varBorderSytle = varBorderSytle & "none "
Case 1
varBorderSytle = varBorderSytle & "solid "
Case -4118
varBorderSytle = varBorderSytle & "dotted "
Case Else
varBorderSytle = varBorderSytle & "solid "
End Select
Select Case r.Borders(b).Weight
Case 1
varBorderWidth = varBorderWidth & "1px "
Case -4138
varBorderWidth = varBorderWidth & "2px "
Case 4
varBorderWidth = varBorderWidth & "3px "
Case 2
varBorderWidth = varBorderWidth & "1px "
Case Else
varBorderWidth = varBorderWidth & "1px "
End Select
varBorderColor = varBorderColor & "rgb(" & color2rgb(r.Borders(b).Color) & ") "
Next b
varBorderSytle = varBorderSytle & ";"
varBorderWidth = varBorderWidth & ";"
varBorderColor = varBorderColor & ";"
getBorder = varBorderSytle & " " & varBorderWidth & " " & varBorderColor
End Function
Function getCellDimension(r As Range) As String
getCellDimension = "width=" & Chr(34) & r.Width * 96 / 72 & "" & Chr(34) & " height=" & Chr(34) & r.Height * 96 / 72 & "" & Chr(34)
End Function
Function getFontStyle(r As Range) As String
Dim varFontColor As Variant
Dim varFontName As Variant
Dim varFontStyle As Variant
Dim varFontSize As Variant
Dim varFontBold As Variant
Dim varFontItalic As Variant
Dim varTextAlign As Variant
varFontColor = "color: rgb(" & color2rgb(r.DisplayFormat.Font.Color) & "); "
varFontName = "font-family: " & r.Font.Name & "; "
varFontSize = "font-size: " & r.DisplayFormat.Font.Size & "pt; "
varFontBold = "font-weight: normal; "
If r.DisplayFormat.Font.Bold Then varFontBold = "font-weight: bold; "
varFontStyle = "font-style: normal; "
If r.DisplayFormat.Font.Italic Then varFontStyle = "font-style: italic; "
Select Case r.HorizontalAlignment
Case -4131
varTextAlign = "text-align: left; "
Case -4152
varTextAlign = "text-align: right; "
Case -4108
varTextAlign = "text-align: center; "
Case -4130
varTextAlign = "text-align: justify; "
Case 1
Select Case Application.Evaluate("TYPE(" & r.Address(0, 0, external:=True) & ")")
Case 1
varTextAlign = "text-align: right; "
Case 2
varTextAlign = "text-align: left; "
Case 4, 16
varTextAlign = "text-align: center; "
Case Else
varTextAlign = "text-align: start; "
End Select
End Select
Dim strCSS As String
strCSS = varFontColor & varFontName & varFontSize & varFontBold & varFontStyle & varTextAlign
getFontStyle = strCSS
End Function
Function color2rgb(varColor As Variant) As String
color2rgb = Format((varColor Mod 256), "00") & ", " & Format(((varColor \ 256) Mod 256), "00") & ", " & Format((varColor \ 65536), "00")
End Function
Additionally I would suggest to add a css-style wihtin the final html-file:
td {
padding:1pt 4pt 1pt 4pt;
}
Related
I have a main form and a tabular sub form in it. I am applying multiple filters to filter my main form but my subform is linked with parent and child field property so I am able to apply filter on one field only.
How can I apply the same filters in my subform to what I have in my main form?
Below is my code to help you to understand:
Private Sub Filtermainform()
Dim strWhere As String
'Make string
If Nz(Me.Combo56, "") <> "" Then
If IsNumeric(Me.Combo56) Then
strWhere = strWhere & "[" & Me.Combo54 & "] = " & Me.Combo56 & " AND "
Else
strWhere = strWhere & "[" & Me.Combo54 & "] = '" & Me.Combo56 & "' AND "
End If
End If
If Nz(Me.Combo109, "") <> "" Then
If IsNumeric(Me.Combo109) Then
strWhere = strWhere & "[" & Me.Combo107 & "] = " & Me.Combo109 & " AND "
Else
strWhere = strWhere & "[" & Me.Combo107 & "] = '" & Me.Combo109 & "' AND "
End If
End If
If Nz(Me.Combo112, "") <> "" Then
If IsNumeric(Me.Combo112) Then
strWhere = strWhere & "[" & Me.Combo111 & "] = " & Me.Combo112 & " AND "
Else
strWhere = strWhere & "[" & Me.Combo111 & "] = '" & Me.Combo112 & "' AND "
End If
End If
If Nz(Me.Combo114, "") <> "" Then
If IsNumeric(Me.Combo114) Then
strWhere = strWhere & "[" & Me.Combo113 & "] = " & Me.Combo114 & " AND "
Else
strWhere = strWhere & "[" & Me.Combo113 & "] = '" & Me.Combo114 & "' AND "
End If
End If
If Nz(Me.Combo116, "") <> "" Then
If IsNumeric(Me.Combo116) Then
strWhere = strWhere & "[" & Me.Combo115 & "] = " & Me.Combo116 & " AND "
Else
strWhere = strWhere & "[" & Me.Combo115 & "] = '" & Me.Combo116 & "' AND "
End If
End If
If Nz(Me.Combo118, "") <> "" Then
If IsNumeric(Me.Combo118) Then
strWhere = strWhere & "[" & Me.Combo117 & "] = " & Me.Combo118 & " AND "
Else
strWhere = strWhere & "[" & Me.Combo117 & "] = '" & Me.Combo118 & "' AND "
End If
End If
If Nz(Me.Combo120, "") <> "" Then
If IsNumeric(Me.Combo120) Then
strWhere = strWhere & "[" & Me.Combo119 & "] = " & Me.Combo120 & " AND "
Else
strWhere = strWhere & "[" & Me.Combo119 & "] = '" & Me.Combo120 & "' AND "
End If
End If
If Nz(Me.Combo122, "") <> "" Then
If IsNumeric(Me.Combo122) Then
strWhere = strWhere & "[" & Me.Combo121 & "] = " & Me.Combo122 & " AND "
Else
strWhere = strWhere & "[" & Me.Combo121 & "] = '" & Me.Combo122 & "' AND "
End If
End If
If Nz(Me.Combo124, "") <> "" Then
If IsNumeric(Me.Combo124) Then
strWhere = strWhere & "[" & Me.Combo123 & "] = " & Me.Combo124 & " AND "
Else
strWhere = strWhere & "[" & Me.Combo123 & "] = '" & Me.Combo124 & "' AND "
End If
End If
'Apply filter
If strWhere <> "" Then
strWhere = Left(strWhere, Len(strWhere) - 5) 'Remove the extra AND
Me.Filter = strWhere
Me.FilterOn = True
Else
Me.Filter = ""
Me.FilterOn = False
End If
You can have multiple fields in the MasterField and ChildField specification, like:
[Id];[FilterField]
[FK];[FilterField]
To remove the filter, double the first field, as you cannot modify either specification to have another count of fields than the other(!), thus:
[Id];[Id]
[FK];[FK]
So I've got the code below (not all of it is grey for some reason)
Private Sub CmdEdit_Click()
Me.Tableinform.Requery
Dim rs As DAO.Recordset
Set rs = Me.Tableinform.Form.RecordsetClone
'get data to textbox control
With rs
If .RecordCount > 0 Then
With Me.Tableinform.Form.Recordset
Me.ShowIDbox = .Fields("[ID]").Value
Me.CompbyDD = .Fields("[Received By]")
Me.Date1 = .Fields("[Date Received]")
Me.Date2 = .Fields("[Date Processed]")
Me.ReqType = .Fields("[Request Type]")
Me.InsName = .Fields("[Insured Name]")
Me.RiskNo = .Fields("[Risk Number]")
Me.EndtRef = .Fields("[Endorsement Reference]")
Me.EOCNo = .Fields("[EOC Number]")
Me.Tech = .Fields("[Technician]")
Me.BillIns = .Fields("[Billing Instructions]")
Me.Addrecord.Caption = "Update"
Me.CmdEdit.Enabled = False
Me.cmdDuplicate.Enabled = True
Me.CmdDelete.Enabled = True
End With
End If
End With
End Sub
After one Edit and Update, the edit function throws out Error '3021' No Current Record?
Please show me where I am going wrong with this.
Add/Update button as follows:
If Me.ShowIDbox.Value = "" Then
CurrentDb.Execute "INSERT INTO fmdatatable( [Received By], [Date Received], [Date Processed], [Request Type], [Insured Name], [Risk Number], [Endorsement Reference], [EOC Number], [Technician], [Billing Instructions]) " & _
" VALUES ('" & Me.CompbyDD & "','" & Me.Date1 & "','" & Me.Date2 & "','" & Me.ReqType & "','" & Me.InsName & "','" & Me.RiskNo & "','" & Me.EndtRef & "','" & Me.EOCNo & "','" & Me.Tech & "','" & Me.BillIns & "')"
Else
CurrentDb.Execute "UPDATE fmdatatable SET [Received By]='" & Me.CompbyDD & "'" & _
", [Date Received]='" & Me.Date1 & "'" & _
", [Date Processed]='" & Me.Date2 & "'" & _
", [Request Type]='" & Me.ReqType & "'" & _
", [Insured Name]='" & Me.InsName & "'" & _
", [Risk Number]='" & Me.RiskNo & "'" & _
", [Endorsement Reference]='" & Me.EndtRef & "'" & _
", [EOC Number]='" & Me.EOCNo & "'" & _
", [Technician]='" & Me.Tech & "'" & _
", [Billing Instructions]='" & BillIns & "'" & _
" WHERE [ID]=" & Me.ShowIDbox.Value
End If
Me.CompbyDD = "-Please Select-"
Me.Date1 = ""
Me.Date2 = ""
Me.ReqType = "-Please Select-"
Me.InsName = ""
Me.RiskNo = ""
Me.EndtRef = ""
Me.EOCNo = ""
Me.Tech = ""
Me.BillIns = "-Please Select-"
Me.ShowIDbox = ""
Me.Addrecord.Caption = "Add Record"
Me.CmdEdit.Enabled = True
Me.cmdDuplicate.Enabled = False
Me.CmdDelete.Enabled = False
Tableinform.Form.Requery
This edit works once, then all subsequent later edits are throwing errors out.
I am pulling data from database into a recordset then converting to array and then writing to a CSV.
In the database all date values are stored as timestamps in this format.
2016-05-04 08:00:00.000000
But when I write to the CSV file the timestamp does not include the milliseconds.
Anyone know how to preserve the milliseconds?
Does the data in the recordset include the milliseconds?
On Error Resume Next
Dim sPassword
Dim sUserID
Dim sDefaultLib
Dim sSystem
Dim cs
Dim rc
Dim objIEDebugWindow
sDefaultLib = *library*
sUserID = *userid*
sPassword = *password*
sSystem = *system*
cs = *connectionString*
Set con = CreateObject("ADODB.Connection")
Set data = CreateObject("ADODB.Recordset")
con.Open cs, sUserID, sPassword
rc = con.State
If (rc = 1) Then
strQuery = "SELECT * FROM Library.Table FETCH FIRST 15 ROWS ONLY FOR READ ONLY WITH UR"
data.CursorLocation = adUseClient
data.Open strQuery, con
Set filsSysObj = CreateObject("Scripting.FileSystemObject")
Dim theYear
Dim theMonth
Dim theDay
Dim mDate
mDate = Date()
theYear = DatePart("yyyy", mDate)
theMonth = Right(String(2, "0") & DatePart("m", mDate), 2)
theDate = Right(String(2, "0") & DatePart("d", mDate), 2)
mDate = theYear & theMonth & theDate
Set csvFile = filsSysObj.OpenTextFile("C:\SampleFile_" & mDate & ".csv", 8, True)
columnCount = data.Fields.Count
Set i = 0
For Each field In data.Fields
i= i + 1
If (i <> columnCount) Then
csvFile.Write Chr(34) & field.Name & Chr(34) & ","
Else
csvFile.Write Chr(34) & field.Name & Chr(34)
End If
Next
csvFile.Write vbNewLine
End If
rowCount = data.RecordCount
row = 0
Dim row
Dim column
Dim resultsArray
Dim dateArray
resultsArray = data.GetRows
debug "hi"
i = 0
Do Until i>5
MsgBox(i)
i = i + 1
'debug "in"
'Dim value
'Dim dArray()
'debug "in"
'value = Chr(34) & CStr(data.Fields(17).Value) & Chr(34) & ","
'dArray = additem(dArray, value)
'data.MoveNext
'dateArray = dArray
Loop
debug "out"
For row = 0 To UBound(resultsArray, 2)
For column = 0 To UBound(resultsArray, 1)
If row = UBound(resultsArray, 2) And column = UBound(resultsArray, 1) Then
csvFile.Write Chr(34) & resultsArray(column, row) & Chr(34)
Else
If column = 0 Then
csvFile.Write Chr(34) & formatDate(resultsArray(column, row)) & Chr(34) & ","
ElseIf column = 19 Then
csvFile.Write Chr(34) & FormatDateTime(resultsArray(column, row),4) & Chr(34) & ","
ElseIf column = 18 Then
csvFile.Write Chr(34) & formatDate(resultsArray(column, row)) & Chr(34) & ","
'ElseIf column = 17 Then
'csvFile.Write Chr(34) & formatDate(resultsArray(column, row)) & Chr(34) & ","
Else
csvFile.Write Chr(34) & resultsArray(column, row) & Chr(34) & ","
End If
End If
Next
csvFile.Write vbNewLine
Next
csvFile.close
'----------------------Helper Functions are below-----------------------------
Sub Debug(myText)
'Dim objIEDebugWindow must be defined globally
'Call like this "Debug variableName"
'Uncomment the next line to turn off debugging
'Exit Sub
If Not IsObject(objIEDebugWindow) Then
Set objIEDebugWindow = CreateObject("InternetExplorer.Application")
objIEDebugWindow.Navigate "about:blank"
objIEDebugWindow.Visible = True
objIEDebugWindow.ToolBar = False
objIEDebugWindow.Width = 200
objIEDebugWindow.Height = 300
objIEDebugWindow.Left = 10
objIEDebugWindow.Top = 10
Do While objIEDebugWindow.Busy
WScript.Sleep 100
Loop
objIEDebugWindow.Document.Title = "IE Debug Window"
objIEDebugWindow.Document.Body.InnerHTML = "<b>" & Now & "</b></br>"
End If
objIEDebugWindow.Document.Body.InnerHTML = objIEDebugWindow.Document.Body.InnerHTML & myText & "<br>" & vbCrLf
End Sub
Function formatDate(sDate)
Dim theYear
Dim theMonth
Dim theDay
Dim formattedDate
theYear = Year(sDate)
theMonth = Right(String(2,"0") & DatePart("m", sDate),2)
theDay = Right(String(2,"0") & DatePart("d", sDate),2)
formattedDate = theYear & "-" & theMonth & "-" & theDate
formatDate = formattedDate
End Function
The only field I am having issues with is field 17 of the recordset.
It is a timestamp datatype from a DB2 database.
The issue was the format is a timestamp in DB2 database. When i pull into a recordset it loses the milliseconds. My solution was to modify the query to add an extra row that pulls in only milliseconds and then later concatenate that back to the date. Please see below. Thanks for everyones help.
if(rc = 1) then
logFile.write FormatDateTime(Now(), 3) & ": Database connection successful" & vbNewLine
logFile.write FormatDateTime(Now(), 3) &": Default Library: " & sDefaultLib & vbNewLine
logFile.write FormatDateTime(Now(), 3) & ": Signed into server as: " & sUserID & vbNewLine
logFile.write FormatDateTime(Now(), 3) & ": System: " & sSystem & vbNewLine
strQuery = "SELECT ws_date, groupcd, userid, firstname, lastname, clientcd, unitcd, categorycd, category, activity, wrktype, subwrktype, step_begin, step_end, report_indicator, report_indicator, count, event_dattim, key_date, key_time, key_milsec, microsecond(event_dattim) FROM *Library.Name* FOR READ ONLY WITH UR"
data.CursorLocation = adUseClient
data.open strQuery, con
if data.EOF then
logFile.write FormatDateTime(Now(), 3) & ": The query returned no data"
logFile.write FormatDateTime(Now(), 3) & ": ---------------- The script DailyWorkstepReport.vbs file was abended at " & Now() &". There was no worksteps file created. ----------------" & vbNewLine
logFile.close
end if
columnCount = data.Fields.Count
columnCount = columnCount - 1
Set filsSysObj = CreateObject("Scripting.FileSystemObject")
Set csvFile = filsSysObj.OpenTextFile("C:\VBScript\Dailys\" & fname, 8, True)
set i = 0
for each field in data.Fields
i= i + 1
if i < columnCount then
csvFile.Write chr(34) & field.name & chr(34) & ","
elseif i = columnCount then
csvFile.Write chr(34) & field.name & chr(34)
else
exit for
end if
next
csvFile.Write vbNewLine
else
logFile.write FormatDateTime(Now(), 3) & ": Database connection was unsuccessful. Database Connection Return Code: " & rc
logFile.write FormatDateTime(Now(), 3) & ": ---------------- The script DailyWorkstepReport.vbs file was abended at " & Now() &". ----------------" & vbNewLine
logFile.close
csvfile.close
wscript.quit
end if
dim row
dim column
dim resultsArray
resultsArray = data.GetRows
dim arrayRows
arrayRows = ubound(resultsArray, 2)
if arrayRows <> 0 then
logFile.write FormatDateTime(Now(), 3) & ": " & (arrayRows + 1) & " rows were successfully read into the array for file " & fname & vbnewline
for row = 0 to UBound(resultsArray, 2)
for column = 0 to (UBound(resultsArray, 1) - 1)
if row = Ubound(resultsArray, 2) and column = (ubound(resultsArray, 1) - 1) then
csvFile.Write chr(34) & resultsArray(column, row) & chr(34)
else
if column = 0 then
csvFile.Write chr(34) & formatDate(resultsArray(column, row)) & chr(34) & ","
elseif column = 19 then
csvFile.Write chr(34) & FormatDateTime(resultsArray(column, row),4) & chr(34) & ","
elseif column = 18 then
csvFile.Write chr(34) & formatDate(resultsArray(column, row)) & chr(34) & ","
elseif column = 17 then
Dim fDate
fDate = formatDate(resultsArray(column, row)) & " " & FormatDateTime(resultsArray(column, row),4) & ":" & second(resultsArray(column,row)) & "." & resultsArray((ubound(resultsArray, 1)), row)
csvFile.Write chr(34) & fDate & chr(34) & ","
else
csvFile.Write chr(34) & resultsArray(column, row) & chr(34) & ","
end if
end if
next
csvFile.Write vbNewLine
next
logfile.write FormatDateTime(Now(), 3) & ": " & (row) & " rows have been written to " & fname &vbNewLine
else
logFile.write FormatDateTime(Now(), 3) & ": There was no data in the query results array for file " & fname & vbNewLine
logFile.write FormatDateTime(Now(), 3) & ": ---------------- The script DailyWorkstepReport.vbs file was abended at " & Now() &". ----------------" & vbNewLine
logfile.close
csvfile.close
wscript.quit
end if
csvFile.close
logfile.write "---------------- DailyWorkstepReport.vbs script successfully ended at " & Now() & "----------------" & vbNewLine
logfile.close
wscript.quit
REM ----------------------Helper Functions are below-----------------------------
Sub Debug( myText )
'Dim objIEDebugWindow must be defined globally
'Call like this "Debug variableName"
'Uncomment the next line to turn off debugging
'Exit Sub
If Not IsObject( objIEDebugWindow ) Then
Set objIEDebugWindow = CreateObject( "InternetExplorer.Application" )
objIEDebugWindow.Navigate "about:blank"
objIEDebugWindow.Visible = True
objIEDebugWindow.ToolBar = False
objIEDebugWindow.Width = 200
objIEDebugWindow.Height = 300
objIEDebugWindow.Left = 10
objIEDebugWindow.Top = 10
Do While objIEDebugWindow.Busy
WScript.Sleep 100
Loop
objIEDebugWindow.Document.Title = "IE Debug Window"
objIEDebugWindow.Document.Body.InnerHTML = "<b>" & Now & "</b></br>"
End If
objIEDebugWindow.Document.Body.InnerHTML = objIEDebugWindow.Document.Body.InnerHTML & myText & "<br>" & vbCrLf
End Sub
function formatDate(sDate)
Dim theYear
Dim theMonth
Dim theDay
Dim formattedDate
theYear = Year(sDate)
theMonth = Right(String(2,"0") & DatePart("m", sDate),2)
theDay = Right(String(2,"0") & DatePart("d", sDate),2)
formattedDate = theYear & "-" & theMonth & "-" & theDate
formatDate = formattedDate
end function
When I click on save, I get the message:
You have an error in your SQL syntax;Check the manual that corresponds to your mySQL Server version for the right Syntax to use near 'idDrug=21' at line 21
Here is my code:
Private Sub cmdSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdSave.Click
Dim i As Integer
Dim xid As Integer
Dim xQTY(0) As Integer
Dim xQTY_ID(0) As Integer
Dim xCount As Integer
Dim xCounter_ID(0) As Integer
'Dim sqlstrx(5) As String
xid = 0
If lstitems.Items.Count > 0 Then
If Split(Me.Text, " - ")(1) = "Add" Then
sqlSTR = "INSERT INTO orders (CustID, Cust_Name, order_date) " & _
"VALUES (" & txtcustid.Text & ", " _
& "'" & txtcustname.Text & "', " _
& "'" & Format(dttoday.Value, "yyyy-MM-dd") & "')"
ExecuteSQLQuery(sqlSTR)
sqlSTR = "SELECT * FROM orders ORDER BY order_no DESC"
ExecuteSQLQuery(sqlSTR)
xid = sqlDT.Rows(0)("order_no")
For i = 0 To lstitems.Items.Count - 1
sqlSTR = "INSERT INTO orders_detail (order_no, idDrug, DrugName, Unit_Cost, qty, totalcost) " & _
"VALUES (" & xid & ", " _
& lstitems.Items(i).Text & ", " _
& "'" & lstitems.Items(i).SubItems(1).Text & "', " _
& "'" & lstitems.Items(i).SubItems(2).Text & "', " _
& lstitems.Items(i).SubItems(3).Text & ", " _
& lstitems.Items(i).SubItems(4).Text & ")"
ExecuteSQLQuery(sqlSTR)
'UPDATE STOCKS
sqlSTR = "UPDATE stockbalances SET ItemQuantity = ItemQuantity -" & CDbl(lstitems.Items(i).SubItems(3).Text) & _
"WHERE idDrug =" & lstitems.Items(i).Text
ExecuteSQLQuery(sqlSTR)
Next
Else
'delete first
For i = 0 To UBound(deleteID)
ExecuteSQLQuery("DELETE FROM Orders_detail WHERE order_no =" & txtorderno.Text & " AND idDrug =" & deleteID(i))
sqlSTR = "UPDATE stockbalances SET ItemQuantity = ItemQuantity +" & Delete_QTY(i) & _
" WHERE idDrug =" & deleteID(i)
ExecuteSQLQuery(sqlSTR)
Next
For i = 0 To UBound(deleteID)
ReDim deleteID(i)
deleteID(i) = 0
Next
del = 0
'--
'If lstitems.Items.Count > 0 Then
For i = 0 To lstitems.Items.Count - 1
'MsgBox(stockID & " " & lstitems.Items(i).Text)
sqlSTR = "SELECT * FROM orders_detail WHERE order_no =" & stockID & " AND idDrug =" & lstitems.Items(i).Text
ExecuteSQLQuery(sqlSTR)
If sqlDT.Rows.Count > 0 Then
ReDim Preserve xQTY(i), xQTY_ID(i)
xQTY(i) = sqlDT.Rows(0)("QTY")
'xQTY_ID(i) = sqlDT.Rows(0)("Item_ID")
End If
'MsgBox(sqlDT.Rows(0)("QTY"))
Next
For i = 0 To lstitems.Items.Count - 1
'MsgBox(xQTY_ID(i))
If lstitems.Items(i).Index <= (UBound(xQTY)) Then
If CDbl(lstitems.Items(i).SubItems(4).Text) < xQTY(i) Then
'MsgBox(xQTY(i) - CDbl(lstitems.Items(i).SubItems(4).Text))
If xQTY(i) > 0 Then
sqlSTR = "UPDATE orders_detail SET qty =" & lstitems.Items(i).SubItems(4).Text & ", " _
& "totalcost =" & lstitems.Items(i).SubItems(3).Text * lstitems.Items(i).SubItems(4).Text & _
" WHERE Order_no =" & stockID & " AND idDrug=" & lstitems.Items(i).Text
ExecuteSQLQuery(sqlSTR)
'UPDATE STOCKS
sqlSTR = "UPDATE stockBalances SET ItemQuantity = ItemQuantity + " & (xQTY(i) - CDbl(lstitems.Items(i).SubItems(4).Text)) & _
" WHERE idDrug =" & lstitems.Items(i).Text
ExecuteSQLQuery(sqlSTR)
End If
ElseIf CDbl(lstitems.Items(i).SubItems(4).Text) > xQTY(i) Then
If xQTY(i) > 0 Then
sqlSTR = "UPDATE orders_detail SET qty =" & lstitems.Items(i).SubItems(4).Text & ", " _
& "totalcost =" & lstitems.Items(i).SubItems(3).Text * lstitems.Items(i).SubItems(4).Text & _
" WHERE order_no =" & stockID & " AND idDrug=" & lstitems.Items(i).Text
ExecuteSQLQuery(sqlSTR)
'UPDATE STOCKS
sqlSTR = "UPDATE Stockbalances SET ItemQuantity = ItemQuantity - " & (CDbl(lstitems.Items(i).SubItems(4).Text) - xQTY(i)) & _
" WHERE idDrug =" & lstitems.Items(i).Text
ExecuteSQLQuery(sqlSTR)
End If
End If
End If
Next
' End If
'search for new item
sqlSTR = "SELECT * FROM orders_detail WHERE order_no =" & stockID & " ORDER BY Order_Dtl ASC"
ExecuteSQLQuery(sqlSTR)
xCount = sqlDT.Rows.Count
For i = 0 To sqlDT.Rows.Count - 1
ReDim Preserve xCounter_ID(i)
xCounter_ID(i) = sqlDT.Rows(i)("idDrug")
' xCount = i + 1
Next
'check
If lstitems.Items.Count > xCount Then
For i = 0 To lstitems.Items.Count - 1
If i > UBound(xCounter_ID) Then
'MsgBox(lstitems.Items(i).Text)
sqlSTR = "INSERT INTO orders_detail (order_no, idDrug, DrugName, price, qty, totalcost) " & _
"VALUES (" & txtorderno.Text & ", " _
& lstitems.Items(i).Text & ", " _
& "'" & lstitems.Items(i).SubItems(0).Text & "', " _
& "'" & lstitems.Items(i).SubItems(1).Text & "', " _
& lstitems.Items(i).SubItems(2).Text & ", " _
& lstitems.Items(i).SubItems(3).Text & ", " _
& lstitems.Items(i).SubItems(4).Text & ")"
ExecuteSQLQuery(sqlSTR)
'UPDATE STOCKS
sqlSTR = "UPDATE stockbalances SET ItemQuantity = ItemQuantity -" & CDbl(lstitems.Items(i).SubItems(4).Text) & _
"WHERE idDrug =" & lstitems.Items(i).Text
ExecuteSQLQuery(sqlSTR)
End If
Next
End If
End If
Else
MsgBox("Can't save without details !!", MsgBoxStyle.Exclamation, xTitlename)
Exit Sub
End If
MsgBox("Record has been saved !!", MsgBoxStyle.Information, xTitlename)
sqlSTR = "SELECT distinct orders.order_no AS 'Order No.', Cust_Name as 'Customer Name', order_date AS 'Date', sum(totalcost) AS 'TOTAL DUE' FROM orders_detail " & _
"INNER JOIN orders ON orders_detail.order_no = orders.order_no " & _
"WHERE order_date ='" & Format(dttoday.Value, "yyyy-MM-dd") & "' GROUP BY orders.order_no, Cust_Name, order_date"
FillListView(ExecuteSQLQuery(sqlSTR), FrmORDERLIST.lstorder, 0)
Me.Close()
End Sub
It is impossible to fix all of your code and to be precise what is the exact cause of your error.
Suffice to say that you never should do a database application using that kind of string concatenation approach. Any of your text fields could cause the error because it contains single quotes or any of your date items could cause the error because it is not formatted how the database requires. (Same for decimals and other floating point values).
To solve this problems (and to avoid the dangerous Sql Injection scenarion) exists the parameterized queries approach.
So, just an example on what you need to do for every line of your sql commands
sqlSTR = "INSERT INTO orders_detail (order_no, idDrug, DrugName, " & _
"Unit_Cost, qty, totalcost) VALUES (" & _
"#id, #iddrug, #dname,#unit, #qty, #total)"
Using cmd = new MySqlCommand(sqlStr, connection)
cmd.Parameters.AddWithValue("#id", xid)
cmd.Parameters.AddWithValue("#idrug", Convert.ToInt32(lstitems.Items(i).Text))
cmd.Parameters.AddWithValue("#dname", lstitems.Items(i).SubItems(1).Text)
cmd.Parameters.AddWithValue("#unit", lstitems.Items(i).SubItems(2).Text)
cmd.Parameters.AddWithValue("#qty", Convert.ToDecimal(lstitems.Items(i).SubItems(3).Text ))
cmd.Parameters.AddWithValue("#total", Convert.ToDecimal(lstitems.Items(i).SubItems(4).Text))
cmd.ExecuteNonQuery()
End Using
Notice how, in a parameterized query, you could specify the datatype of the value passed for the parameter using the Convert.ToXXXXX method. In this way the framework code could prepare the appropriate formatting of your values to be passed to the database engine.
Not to mention the now readable query text.
I have an MS Access form where the user can select up to four criteria to filter the records returned by a report. In the VBA, I'm trying to build my filter string dynamically based on which fields, if any, the user chose to filter by. The below code is giving me a "Block If without End If" error. What am I doing wrong here?
If (IsNull(frm!employee) = False) Then
strFilter = "Trainee_First_Name + ' ' + Trainee_Last_Name = '" & frm!employee & "'"
If IsNull(frm!sop) = False Then
strFilter = strFilter + " AND sop_number = '" & frm!sop & "'"""
End If
If IsNull(frm!revision) = False Then
strFilter = strFilter + " AND revision_number = '" & frm!revision & "'"
End If
If IsNull(frm!dept) = False Then
strFilter = strFilter + " AND department = '" & frm!dept & "'"
End If
Else
If (IsNull(frm!sop) = False) Then
strFilter = "sop_number = '" & frm!sop & "'"
If (IsNull(frm!employee) = False) Then
strFilter = "Trainee_First_Name + ' ' + Trainee_Last_Name = '" & frm!employee & "'"
End If
If IsNull(frm!revision) = False Then
strFilter = strFilter + " AND revision_number = '" & frm!revision & "'"
End If
If IsNull(frm!dept) = False Then
strFilter = strFilter + " AND department = '" & frm!dept & "'"
End If
Else
If (IsNull(frm!revision) = False) Then
strFilter = "revision_number = '" & frm!revision & "'"
If (IsNull(frm!employee) = False) Then
strFilter = " AND Trainee_First_Name + ' ' + Trainee_Last_Name = '" & frm!employee & "'"
End If
If IsNull(frm!sop) = False Then
strFilter = strFilter + " AND sop_number = '" & frm!sop & "'"""
End If
If IsNull(frm!dept) = False Then
strFilter = strFilter + " AND department = '" & frm!dept & "'"
End If
Else
If IsNull(frm!dept) = False Then
strFilter = "department = '" & frm!dept & "'"
If (IsNull(frm!employee) = False) Then
strFilter = " AND Trainee_First_Name + ' ' + Trainee_Last_Name = '" & frm!employee & "'"
End If
If IsNull(frm!sop) = False Then
strFilter = strFilter + " AND sop_number = '" & frm!sop & "'"""
End If
If IsNull(frm!revision) = False Then
strFilter = strFilter + " AND revision_number = '" & frm!revision & "'"
End If
End If
Any advice you could give me to improve this code would be appreciated.
That code avoids " AND " at the beginning of strFilter. However the logic is challenging to follow and it uses multiple variations on the same basic themes.
Use a simpler approach. You're interested in the values contained in 4 form controls:
frm!employee
frm!sop
frm!Revision
frm!dept
Examine each of them in turn and, for any which contain a value, add a segment starting with " AND " to strFilter. Afterwards, if strFilter contains any text, you know it starts with " AND " so you can simply discard the first 5 characters.
strFilter = vbNullString ' <- make it explicit
If Len(Trim(frm!employee) & vbNullString) > 0 Then
strFilter = strFilter & _
" AND Trainee_First_Name & ' ' & Trainee_Last_Name = '" & _
frm!employee & "'"
End If
If Len(Trim(frm!sop) & vbNullString) > 0 Then
strFilter = strFilter & " AND sop_number = '" & frm!sop & "'"
End If
If Len(Trim(frm!Revision) & vbNullString) > 0 Then
strFilter = strFilter & " AND revision_number = '" & _
frm!Revision & "'"
End If
If Len(Trim(frm!dept) & vbNullString) > 0 Then
strFilter = strFilter & " AND department = '" & frm!dept & "'"
End If
If Len(strFilter) > 0 Then
' discard " AND " from beginning of string
strFilter = Mid(strFilter, 6)
End If
MsgBox "strFilter ->" & strFilter & "<-"
The issue is that your else... if clause aren't terminated with end if. You either need to use ElseIf or
Else
If ...
End If
Else...
I've modified your code below to use the latter syntax. Notice the End If lines below.
Note: You don't need **, that's just to call attention to it in your code block!
If (IsNull(frm!employee) = False) Then
strFilter = "Trainee_First_Name + ' ' + Trainee_Last_Name = '" & frm!employee & "'"
If IsNull(frm!sop) = False Then
strFilter = strFilter + " AND sop_number = '" & frm!sop & "'"""
End If
If IsNull(frm!revision) = False Then
strFilter = strFilter + " AND revision_number = '" & frm!revision & "'"
End If
If IsNull(frm!dept) = False Then
strFilter = strFilter + " AND department = '" & frm!dept & "'"
End If
Else
If (IsNull(frm!sop) = False) Then
strFilter = "sop_number = '" & frm!sop & "'"
If (IsNull(frm!employee) = False) Then
strFilter = "Trainee_First_Name + ' ' + Trainee_Last_Name = '" & frm!employee & "'"
End If
If IsNull(frm!revision) = False Then
strFilter = strFilter + " AND revision_number = '" & frm!revision & "'"
End If
If IsNull(frm!dept) = False Then
strFilter = strFilter + " AND department = '" & frm!dept & "'"
End If
**End If**
Else
If (IsNull(frm!revision) = False) Then
strFilter = "revision_number = '" & frm!revision & "'"
If (IsNull(frm!employee) = False) Then
strFilter = " AND Trainee_First_Name + ' ' + Trainee_Last_Name = '" & frm!employee & "'"
End If
If IsNull(frm!sop) = False Then
strFilter = strFilter + " AND sop_number = '" & frm!sop & "'"""
End If
If IsNull(frm!dept) = False Then
strFilter = strFilter + " AND department = '" & frm!dept & "'"
End If
**End If**
Else
If IsNull(frm!dept) = False Then
strFilter = "department = '" & frm!dept & "'"
If (IsNull(frm!employee) = False) Then
strFilter = " AND Trainee_First_Name + ' ' + Trainee_Last_Name = '" & frm!employee & "'"
End If
If IsNull(frm!sop) = False Then
strFilter = strFilter + " AND sop_number = '" & frm!sop & "'"""
End If
If IsNull(frm!revision) = False Then
strFilter = strFilter + " AND revision_number = '" & frm!revision & "'"
End If
**End If**
End If