Format DateTime to DateTime with Milliseconds - csv
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
Related
When I run this code, it is counting every time, however it is not resetting for the month or the year
Aim is to reset Month Value and Year value every month and every year, however, it is not resetting. Please help. Private Sub Proforma_Number_Generator_Command_Click() Dim vLastM As Variant Dim accM As Integer Dim vLastY As Variant Dim accY As Integer 'Sets the date of the Proforma Invoice Number to Today' 'Me.Proforma_Invoice_Date = Format(Date, "yyyy-mm-dd") vLastM = DMax("[Month Value]", "[Proforma Invoice Form Table]", _ "PI_Month='" & Me.PI_Month.Value & "' AND PI_Year ='" & _ Me.PI_Year.Value & "'") If IsNull(vLastM) Then accM = 1 Else accM = vLastM + 1 End If Me.Month_Value = accM 'Year' vLastY = DMax("[Year Value]", "[Proforma Invoice Form Table]", _ "PI_Year='" & Me.PI_Year.Value & "'") If IsNull(vLastY) Then accY = 1 Else accY = vLastY + 1 End If Me.Year_Value = accY Me.Order_No = Format("ON" & "-" & Format(Date, "yyyy") & "-" & Me.Year_Value) End Sub
It is confusing what your goal is, as month isn't used, but try this reduced code: Private Sub Proforma_Number_Generator_Command_Click() ' Month. Not used? Me!Month_Value.Value = Nz(DMax("[Month Value]", "[Proforma Invoice Form Table]", _ "PI_Month=" & Me!PI_Month.Value & " AND PI_Year ='" & _ Me.PI_Year.Value & ""), 0) + 1 ' Year. Me!Year_Value.Value = Nz(DMax("[Year Value]", "[Proforma Invoice Form Table]", _ "PI_Year=" & Me!PI_Year.Value & ""), 0) + 1 Me!Order_No.Value = Format("ON" & "-" & Format(Date, "yyyy") & "-" & Me!Year_Value.Value & "-" & ) End Sub
MS Access Query ColumnHidden Property
I've written some VBA code that (a) sets the SQL of a query based on input variables, (b) opens the query in datasheet view, and (c) hides or shows columns based on "true" / "false" values of check boxes in another table. This is considering the "ColumnHidden" property as described in Microsoft Dev Center help. Dev Center Help - ColumnHidden Property When executing the code, (a) and (b) are working as intended. However, I get error 3270, "Property not found" at line fld.Properties("ColumnHidden") = False when executing (c). I've been unable to resolve the issue, even when trying the error handling method described in the Dev Center. Please help! Dim rsLabel As DAO.Recordset, rsCOlumn As DAO.Recordset Dim qryCPQ As DAO.QueryDef Dim strLabel As String, strSQL As String, strColumn As String Dim fld As DAO.Field Dim dbs As DAO.Database Dim prp As DAO.Property Dim AttArray As Variant Dim x As Integer ReDim AttArray(19, 1) For x = 1 To 20 AttArray(x - 1, 1) = "Att" & x Next x strLabel = "SELECT * FROM PM_qryLabels2 WHERE CAT_ID=" & Forms!CM_frmCollectionReportPre!cboFamily Set rsLabel = CurrentDb.OpenRecordset(strLabel, dbOpenSnapshot) rsLabel.MoveFirst For x = 1 To 20 If Not IsNull(rsLabel.Fields("Att" & x)) Then AttArray(x - 1, 1) = rsLabel.Fields("Att" & x) Else AttArray(x - 1, 1) = "Att" & x End If Next x With CurrentDb Set qryCPQ = .QueryDefs("CM_qryCollectionReport") strSQL = "SELECT CM_qryCollectionEdit2.CATEGORY, CM_qryCollectionEdit2.Part_No, CM_qryCollectionEdit2.CPQ_Material, CM_qryCollectionEdit2.CPQ_LaborMach, CM_qryCollectionEdit2.CPQ_LaborAssy, CM_qryCollectionEdit2.CPQ_LaborPipe, CM_qryCollectionEdit2.CPQ_LaborTest, CM_qryCollectionEdit2.CPQ_LaborPack, CM_qryCollectionEdit2.CPQ_LaborShip, CM_qryCollectionEdit2.CPQ_Sub, " & _ "PM_qryOptions.Att1 As [" & AttArray(0, 1) & "], PM_qryOptions.Att2 As [" & AttArray(1, 1) & "], PM_qryOptions.Att3 As [" & AttArray(2, 1) & "], PM_qryOptions.Att4 As [" & AttArray(3, 1) & "], PM_qryOptions.Att5 As [" & AttArray(4, 1) & "], PM_qryOptions.Att6 As [" & AttArray(5, 1) & "], PM_qryOptions.Att7 As [" & AttArray(6, 1) & "], PM_qryOptions.Att8 As [" & AttArray(7, 1) & "], PM_qryOptions.Att9 As [" & AttArray(8, 1) & "], PM_qryOptions.Att10 As [" & AttArray(9, 1) & "], PM_qryOptions.Att11 As [" & AttArray(10, 1) & "], PM_qryOptions.Att12 As [" & AttArray(11, 1) & "], PM_qryOptions.Att13 As [" & AttArray(12, 1) & "], PM_qryOptions.Att14 As [" & AttArray(13, 1) & "], PM_qryOptions.Att15 As [" & AttArray(14, 1) & "], PM_qryOptions.Att16 As [" & AttArray(15, 1) & "], PM_qryOptions.Att17 As [" & AttArray(16, 1) & "], PM_qryOptions.Att18 As [" & AttArray(17, 1) & "], PM_qryOptions.Att19 As [" & AttArray(18, 1) & "], PM_qryOptions.Att20 As [" & AttArray(19, 1) & "] " & _ "FROM CM_qryCollectionEdit2 INNER JOIN PM_qryOptions ON CM_qryCollectionEdit2.Part_No = PM_qryOptions.Part_No " & _ "WHERE ((CM_qryCollectionEdit2.CAT_ID)=" & Me.cboFamily & " AND ((CM_qryCollectionEdit2.CPQ_Publish)=True));" qryCPQ.SQL = strSQL qryCPQ.Close Set qryCPQ = Nothing End With DoCmd.OpenQuery "CM_qryCollectionReport", , acReadOnly Set dbs = CurrentDb For x = 1 To 20 Set fld = dbs.QueryDefs!CM_qryCollectionReport.Fields(AttArray(x - 1, 1)) fld.Properties("ColumnHidden") = False strColumn = "SELECT * FROM PM_Attributes WHERE CAT_ID=" & Forms!CM_frmCollectionReportPre!cboFamily & " AND [ATTRIBUTE]='" & AttArray(x - 1, 1) & "'" Set rsCOlumn = CurrentDb.OpenRecordset(strColumn, dbOpenSnapshot) If Not rsCOlumn.EOF Then If rsCOlumn![CPQ_Publish] = False Then fld.Properties("ColumnHidden") = True End If End If rsCOlumn.Close Set rsCOlumn = Nothing Set fld = Nothing Next x Set dbs = Nothing DoCmd.Close acForm, "CM_frmCollectionReportPre", acSaveNo Per Eric Von Asmuth's suggestion, I've added in the error handling, so the code now appears as follows. Yet I still receive error 3270 at the same location. Hasn't fixed a thing. Dim rsLabel As DAO.Recordset, rsCOlumn As DAO.Recordset Dim qryCPQ As DAO.QueryDef Dim strLabel As String, strSQL As String, strColumn As String Dim fld As DAO.Field Dim dbs As DAO.Database Dim prp As DAO.Property Dim AttArray As Variant Dim x As Integer Const conErrPropertyNotFound = 3270 ' Turn off error trapping On Error Resume Next ReDim AttArray(19, 1) For x = 1 To 20 AttArray(x - 1, 1) = "Att" & x Next x strLabel = "SELECT * FROM PM_qryLabels2 WHERE CAT_ID=" & Forms!CM_frmCollectionReportPre!cboFamily Set rsLabel = CurrentDb.OpenRecordset(strLabel, dbOpenSnapshot) rsLabel.MoveFirst For x = 1 To 20 If Not IsNull(rsLabel.Fields("Att" & x)) Then AttArray(x - 1, 1) = rsLabel.Fields("Att" & x) Else AttArray(x - 1, 1) = "Att" & x End If Next x 'AFTER FORM IS OPEN, NEED TO HIDE COLUMNS BASEDON CPQ_PUBLISH With CurrentDb Set qryCPQ = .QueryDefs("CM_qryCollectionReport") strSQL = "SELECT CM_qryCollectionEdit2.CATEGORY, CM_qryCollectionEdit2.Part_No, CM_qryCollectionEdit2.CPQ_Material, CM_qryCollectionEdit2.CPQ_LaborMach, CM_qryCollectionEdit2.CPQ_LaborAssy, CM_qryCollectionEdit2.CPQ_LaborPipe, CM_qryCollectionEdit2.CPQ_LaborTest, CM_qryCollectionEdit2.CPQ_LaborPack, CM_qryCollectionEdit2.CPQ_LaborShip, CM_qryCollectionEdit2.CPQ_Sub, " & _ "PM_qryOptions.Att1 As [" & AttArray(0, 1) & "], PM_qryOptions.Att2 As [" & AttArray(1, 1) & "], PM_qryOptions.Att3 As [" & AttArray(2, 1) & "], PM_qryOptions.Att4 As [" & AttArray(3, 1) & "], PM_qryOptions.Att5 As [" & AttArray(4, 1) & "], PM_qryOptions.Att6 As [" & AttArray(5, 1) & "], PM_qryOptions.Att7 As [" & AttArray(6, 1) & "], PM_qryOptions.Att8 As [" & AttArray(7, 1) & "], PM_qryOptions.Att9 As [" & AttArray(8, 1) & "], PM_qryOptions.Att10 As [" & AttArray(9, 1) & "], PM_qryOptions.Att11 As [" & AttArray(10, 1) & "], PM_qryOptions.Att12 As [" & AttArray(11, 1) & "], PM_qryOptions.Att13 As [" & AttArray(12, 1) & "], PM_qryOptions.Att14 As [" & AttArray(13, 1) & "], PM_qryOptions.Att15 As [" & AttArray(14, 1) & "], PM_qryOptions.Att16 As [" & AttArray(15, 1) & "], PM_qryOptions.Att17 As [" & AttArray(16, 1) & "], PM_qryOptions.Att18 As [" & AttArray(17, 1) & "], PM_qryOptions.Att19 As [" & AttArray(18, 1) & "], PM_qryOptions.Att20 As [" & AttArray(19, 1) & "] " & _ "FROM CM_qryCollectionEdit2 INNER JOIN PM_qryOptions ON CM_qryCollectionEdit2.Part_No = PM_qryOptions.Part_No " & _ "WHERE ((CM_qryCollectionEdit2.CAT_ID)=" & Me.cboFamily & " AND ((CM_qryCollectionEdit2.CPQ_Publish)=True));" qryCPQ.SQL = strSQL qryCPQ.Close 'Set qryCPQ = Nothing End With DoCmd.OpenQuery "CM_qryCollectionReport", , acReadOnly Set dbs = CurrentDb For x = 1 To 20 Set fld = dbs.QueryDefs!CM_qryCollectionReport.Fields(AttArray(x - 1, 1)) fld.Properties("ColumnHidden") = False ' Error may have occurred when value was set. ' Display error message or create property when property didn't exist If Err.Number <> 0 Then If Err.Number <> conErrPropertyNotFound Then On Error GoTo 0 MsgBox "Couldn't set property 'ColumnHidden' " & _ "on field '" & fld.Name & "'", vbCritical Else On Error GoTo 0 Set prp = fld.CreateProperty("ColumnHidden", dbLong, False) fld.Properties.Append prp End If End If strColumn = "SELECT * FROM PM_Attributes WHERE CAT_ID=" & Forms!CM_frmCollectionReportPre!cboFamily & " AND [ATTRIBUTE]='" & AttArray(x - 1, 1) & "'" Set rsCOlumn = CurrentDb.OpenRecordset(strColumn, dbOpenSnapshot) If Not rsCOlumn.EOF Then If rsCOlumn![CPQ_Publish] = False Then fld.Properties("ColumnHidden") = True End If End If rsCOlumn.Close Set rsCOlumn = Nothing Set fld = Nothing Set prp = Nothing Next x Set dbs = Nothing DoCmd.Close acForm, "CM_frmCollectionReportPre", acSaveNo Screen shots of error:
If you closely look at the example code in the article you referred to, it includes error capturing, and creating the property if it didn't exist. This is because the property may or may not exist based on unpredictable circumstances. Adapted from the Linked article: Const conErrPropertyNotFound = 3270 ' Turn off error trapping. On Error Resume Next 'Set the field to false here fld.Properties("ColumnHidden") = False ' Error may have occurred when value was set. ' Display error message or create property when property didn't exist If Err.Number <> 0 Then If Err.Number <> conErrPropertyNotFound Then On Error GoTo 0 MsgBox "Couldn't set property 'ColumnHidden' " & _ "on field '" & fld.Name & "'", vbCritical Else On Error GoTo 0 Set prp = fld.CreateProperty("ColumnHidden", dbLong, False) fld.Properties.Append prp End If End If Since you've already set the field to False, you don't need to error trap in case the field doesn't exist when setting it back to True You can also choose to check if the property does exist by iterating through all properties, which is best done in a separate function. This avoids error trapping, but may take longer to run
Reading data from excel merge cells using vb.net
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.
How to combine two strings on a report filter?
I'm writing VBA code for an application in Access for the first time and have created two separate strings to filter a report. The first of these strFilter filters the reports based on criteria in a list box. The second strWhere has been set up to filter the report based on a date input into a pair of text boxes. Both of these string filters work perfectly when used separately. What I want to know is if there is a way to combine the two strings easily so that the user an filter the report based on both the criteria in the list box and the date they have entered in the text boxes. The code I have for the listbox filter when it is added to the reports filter currently looks like this: With Reports![rptFaultRecords] .Filter = strFilter .FilterOn = True I want to add the string to filter by date strWhere next to the strFilter so the report can be filtered by both date and list criteria. All the code I've entered when attempting to do this has given me a run time error 3075. Is it possible for these two strings to be combined easily and if so how can I do it? The rest of the code I've written is below if you need to see it: Private Sub btnAllFaultsFilter_Click() Dim varItem As Variant Dim strRoom As String Dim strFilter As String Dim strDevice As String Dim strCat As String Dim strStatus As String Dim strDateField As String Dim strWhere As String Const strcJetDate = "\#mm\/dd\/yyyy\#" strDateField = "[f_datereported]" If IsDate(Me.txtStartDate) Then strWhere = "(" & strDateField & " >= " & Format(Me.txtStartDate, strcJetDate) & ")" End If If IsDate(Me.txtEndDate) Then If strWhere <> vbNullString Then strWhere = strWhere & " AND " End If strWhere = strWhere & "(" & strDateField & " < " & Format(Me.txtEndDate + 1, strcJetDate) & ")" End If For Each varItem In Me.lstRoom.ItemsSelected strRoom = strRoom & ",'" & Me.lstRoom.ItemData(varItem) & "'" Next varItem If Len(strRoom) = 0 Then strRoom = "Like '*'" Else strRoom = Right(strRoom, Len(strRoom) - 1) strRoom = "IN(" & strRoom & ")" End If For Each varItem In Me.lstDevice.ItemsSelected strDevice = strDevice & ",'" & Me.lstDevice.ItemData(varItem) & "'" Next varItem If Len(strDevice) = 0 Then strDevice = "Like '*'" Else strDevice = Right(strDevice, Len(strDevice) - 1) strDevice = "IN(" & strDevice & ")" End If For Each varItem In Me.lstCategory.ItemsSelected strCat = strCat & ",'" & Me.lstCategory.ItemData(varItem) & "'" Next varItem If Len(strCat) = 0 Then strCat = "Like '*'" Else strCat = Right(strCat, Len(strCat) - 1) strCat = "IN(" & strCat & ")" End If For Each varItem In Me.lstStatus.ItemsSelected strStatus = strStatus & ",'" & Me.lstStatus.ItemData(varItem) & "'" Next varItem If Len(strStatus) = 0 Then strStatus = "Like '*'" Else strStatus = Right(strStatus, Len(strStatus) - 1) strStatus = "IN(" & strStatus & ")" End If strFilter = "[c_roomid] " & strRoom & " AND [f_computername] " & strDevice & " AND [f_faultcategory] " & strCat & " AND [f_faultstatus] " & strStatus With Reports![rptFaultRecords] '.Filter = strFilter .Filter = strFilter .FilterOn = True End With End Sub
change character in all text fields
I need your help. I woulod like to change one char by another but in all database and i have several table and fields. So i'm building a function in VB but that change nothing and i have no error. I think that my condition is false but i don't see how to correct it :/ Public Sub updateField() Dim db As DAO.Database, td As DAO.TableDef, field As DAO.field Dim rs As DAO.Recordset, sSQL As String, sData As String Set db = CurrentDb Change = "\""" replaced = """" 'each table in db For Each tbd In db.TableDefs 'each field in table For Each fld In tbd.Fields 'check if String Data have my character If InStr(1, fld.Name, Change) Then sSQL = "UPDATE " & tbd.Name & " SET " & fld.Name & " = replace([" & fld.Name & "], " & Change & ", " & replaced & ")" db.Execute sSQL End If Next Next End Sub EDIT : I finally find what's wrong. if some people are interested : Set db = CurrentDb Change = "\""" replaced = """" 'each table in db For Each tbd In db.TableDefs 'each field in table For Each fld In tbd.Fields If Left(tbd.Name, 4) <> "MSys" And Left(tbd.Name, 4) <> "~TMP" Then If fld.Type = dbText Or fld.Type = dbMemo Then sSQL = "UPDATE " & tbd.Name & " SET " & fld.Name & " = replace([" & fld.Name & "],'" & Chr(92) + Chr(34) & "','" & Chr(34) & "')" db.Execute sSQL 'Debug.Print (sSQL) End If End If Next Next Thx for your help guys ;)
If it should help there my solution : Public Sub updateField() Dim db As DAO.Database, td As DAO.TableDef, field As DAO.field Dim rs As DAO.Recordset, sSQL As String, sData As String, change As String, replace As String change = "\'" replace = "'" ' simple quote = 39 ' doulbe quote = 34 ' antislash = 92 ' retour chariot = 13 ' n = 110 ' r = 114 Set db = CurrentDb 'each table in db For Each tbd In db.TableDefs 'each field in table For Each fld In tbd.Fields If Left(tbd.Name, 4) <> "MSys" And Left(tbd.Name, 4) <> "~TMP" Then If fld.Type = dbText Or fld.Type = dbMemo Then ' \r\n 'sSQL = "UPDATE " & tbd.Name & " SET [" & fld.Name & "] = replace([" & fld.Name & "],'\r\n','" & Chr(13) & Chr(10) & "');" ' \" 'sSQL = "UPDATE " & tbd.Name & " SET [" & fld.Name & "] = replace([" & fld.Name & "],'" & Chr(92) + Chr(34) & "','" & Chr(34) & "');" 'db.Execute sSQL sSQL = "UPDATE " & tbd.Name & " SET [" & fld.Name & "] = replace([" & fld.Name & "],'\''','''');" db.Execute sSQL 'Debug.Print (sSQL) End If End If Next Next End Sub That's works for me ;)