vba convert msexcel table to json. Ending line not consistant - json

The sub below creates a json file from an Excel table that starts in cells(1,1). The problem is when I drag and drop the generated file in Visual Studio, I get the following message:
The line endings in the following file are not consistent. Do you want
normalize the line endings?
How can I make this sub produce consistent line endings?
Sub CreateWksJON(mywksht As Worksheet, NbofFields As Integer, NbofElements As Integer)
Dim FilePath As String
Dim fieldData As String
Dim i As Integer
Dim j As Integer
Dim objStream
Set objStream = CreateObject("ADODB.Stream")
objStream.Charset = "utf-8"
objStream.Open
FilePath = "E:\Git\ACWB-MSEcelWorksheetTOJson\" & mywksht.Name & ".json"
'Open FilePath For Output As #1
fieldData = "{" & Chr(10) & Chr(13) & """" & mywksht.Name & """" & ": {" & Chr(10) & Chr(13)
objStream.writetext fieldData
fieldData = ""
For j = 1 To NbofFields
i = 1
fieldData = """" & mywksht.Cells(i, j).Value & """" & ": ["
For i = 2 To NbofElements - 2
If IsNumeric(mywksht.Cells(i, j).Value) Then
fieldData = fieldData & mywksht.Cells(i, j).Value & ","
Else
fieldData = fieldData & """" & mywksht.Cells(i, j).Value & """" & ","
End If
Next i
'add the last element of the field
If IsNumeric(mywksht.Cells(i + 1, j).Value) Then
fieldData = fieldData & mywksht.Cells(i + 1, j).Value
Else
fieldData = fieldData & """" & mywksht.Cells(i + 1, j).Value & """"
End If
If j = NbofFields Then
fieldData = fieldData & "]" & Chr(10) & Chr(13)
Else
fieldData = fieldData & "]," & Chr(10) & Chr(13)
End If
objStream.writetext fieldData
Next j
objStream.writetext "}" & Chr(10) & Chr(13) & "}" & Chr(10) & Chr(13)
objStream.SaveToFile FilePath, 2
End Sub
Here is the table
Envelpope_ID CG_MAC CG_Imp CG_SI Weight_Imp Weight_SI
1 20 875 22.225 71700 32522.58942
1 20 875 22.225 98000 44452.0748
1 28 900 22.86 129720 58840.03207
1 38 1000 25.4 129720 58840.03207
1 38 1000 25.4 119840 54358.53718
1 43 1200 30.48 102200 46357.16372
1 43 1200 30.48 94000 42637.7044
1 34 950 24.13 71700 32522.58942
1 20 875 22.225 71700 32522.58942
2 20 875 22.225 71700 32522.58942
2 20 875 22.225 98000 44452.0748
2 28 900 22.86 125000 56699.075
2 38 1000 25.4 125000 56699.075
2 38 1200 30.48 102200 46357.16372
2 43 1200 30.48 94000 42637.7044
2 43 950 24.13 71700 32522.58942
2 34 875 22.225 71700 32522.58942

You could change to VbCrLf, but character naming should work if you do it in the right order.
Cr is ASCII(13) and Lf is ASCII(10) so your line ending should be
chr(13)&chr(10)

Related

Access Update Query using VBA

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

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.

Sorting my spacing from copying listbox data

I am using the below code to copy data from a listbox:
Dim sData As String
Dim X As Integer
'Has the user ticked the use col heads tick box?
If Me.ChkColHeads = True Then
sData = sData & "Account Number" & vbTab & "Advisor Name" & vbTab & vbTab & "Team" & vbTab & vbTab & vbTab & vbTab & vbTab & "Days Lost" & vbTab & vbTab & vbCrLf
End If
'x would be set to row 1 if using column heading in list
For X = 0 To Me.List31.ListCount
If Me.List31.Selected(X) = True Then
sData = sData & Me.List31.Column(0, X) & vbTab & vbTab & Me.List31.Column(1, X) & vbTab & vbTab & Me.List31.Column(2, X) & vbTab & vbTab & Me.List31.Column(3, X) & vbTab & vbTab & Me.List31.Column(4, X) & vbCrLf
End If
Next
'Copy the data to the clipboard
ClipBoard_SetData (sData)
'Let user know that the procedure has been completed
MsgBox "Data copied to clipboard", vbInformation + vbOKOnly, "Copied"
There is also a module that copies it to the clipboard.
My issue it the formatting - Some items are not lined up as they should be as below:
11111 Name1 Team1 0
22222 Name1 Team2
33333 Name1 Team3 5
22222 Name1 Team1 6
1121 Name1 Team3 0
543 Name1 Team3
7654 Name1 Team4
432543 Name1 Team7 0
87654 Name1 Team1 3
Some teams are not lined up and can not figure out why. Any help is appreciated
It's because you use vbTab. But that is correct if you wish to paste the date into, say, Excel.
If you wish text and spaces only, do:
Left(Me.List31.Column(0, X) & Space(16), 20)
or similar. Adjust 16 and 20 to your liking.

Format DateTime to DateTime with Milliseconds

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

VBA import excel into access glitches when excel cell contains double ' '

I am trying to import data from Excel into Access. Both 2010. Everything worked perfectly until I came across a cell that contained [text 'A' text]. Access completely stops the Sub at this point. When I manually change the Excel cell to [text A text] or the '' to ``, everything works perfectly again. But having to manually changing the source Excel defeats the purpose.
How do I import an Excel sheet when one or more cells contain [ 'A' ]?
Thank you in advance for any help.
'This checks if file exsist, imports file, then imports any sequential files.
Option Explicit
Public Sub ImportXL2(bolJustExcelFile As Boolean, Optional bolRefresh As Boolean)
Dim rstXL As DAO.Recordset
Dim x As Integer, y As Long
Dim strPath1 As String, strPath2 As String
Dim strPN As String, strDescription As String, strPrime As String
Dim intOHB As Integer, sngCost As Single, intMin As Integer, intMax As Integer
Dim strCode As Integer, strNumber As String, strDate As String, strQty As Integer, strRepairable As String, strEntity As String
DoCmd.SetWarnings False
DoCmd.RunSQL "DELETE FROM ExcelFile"
If bolJustExcelFile = False Then
DoCmd.RunSQL "DELETE FROM ExcelFileCombined"
End If
For x = 1 To 10
DoCmd.RunSQL "DELETE FROM ExcelFiletemp"
strPath1 = Environ("userprofile") & "\Desktop\Folder\ExcelFile.xlsx"
strPath2 = Environ("userprofile") & "\Desktop\Folder\ExcelFile" & x & ".xlsx"
If x = 1 Then
If FileExists(strPath1) = -1 Then
DoCmd.TransferSpreadsheet acImport, acSpreadsheetTypeExcel12, "ExcelFiletemp", strPath1, False, "A:L"
Else
If bolRefresh = True Then
MsgBox "ExcelFile File Not Found", , "Missing ExcelFile File"
End If
Exit For
End If
Else
If FileExists(strPath2) = -1 And bolJustExcelFile = False Then
DoCmd.TransferSpreadsheet acImport, acSpreadsheetTypeExcel12, "ExcelFiletemp", strPath2, False, "A:L"
Else
GoTo SkipXL
End If
End If
Set rstXL = CurrentDb.OpenRecordset("SELECT * FROM ExcelFiletemp", dbOpenSnapshot)
rstXL.MoveLast
rstXL.MoveFirst
For y = 1 To 4
rstXL.MoveNext
Next y
strEntity = Right(rstXL![F1], 6)
For y = 1 To 4
rstXL.MoveNext
Next y
On Error GoTo ErrHandler
For y = 1 To rstXL.RecordCount - 8
strPN = rstXL![F1]
strDescription = rstXL![F2]
strPrime = rstXL![F3]
intOHB = rstXL![F4]
sngCost = rstXL![F5]
intMin = rstXL![F6]
intMax = rstXL![F7]
strCode = rstXL![F8]
strRepairable = rstXL![F12]
If x = 1 Then
DoCmd.RunSQL "INSERT INTO ExcelFile (PN, Description, Prime, OHB, Cost, Min, Max, Code, Repairable, Entity) VALUES ('" & strPN & "','" & strDescription & "','" & strPrime & "'," & intOHB & "," & sngCost & "," & intMin & "," & intMax & "," & strCode & ",'" & strRepairable & "','" & strEntity & "');"
End If
If bolJustExcelFile = False Then
DoCmd.RunSQL "INSERT INTO ExcelFileCombined (PN, Description, Prime, OHB, Cost, Min, Max, Code, Repairable, Entity) VALUES ('" & strPN & "','" & strDescription & "','" & strPrime & "'," & intOHB & "," & sngCost & "," & intMin & "," & intMax & "," & strCode & ",'" & strRepairable & "','" & strEntity & "');"
End If
rstXL.MoveNext
Next y
rstXL.Close
SkipXL:
Next x
Set rstXL = Nothing
DoCmd.SetWarnings True
ErrHandler:
If Err.Number = 94 Then 'Invalid use of Null
rstXL.MoveNext
End If
End Sub
You can escape single quotes by doubling them up.
Function EscQ(text As String)
EscQ = Replace(text, "'", "''")
End Function
Usage:
DoCmd.RunSQL "INSERT INTO ExcelFileCombined (PN, Description, Prime, OHB, Cost, Min, Max, Code, Repairable, Entity) VALUES ('" & EscQ(strPN) & "','" & EscQ(strDescription) & "','" & EscQ(strPrime) & "'," & intOHB & "," & sngCost & "," & intMin & "," & intMax & "," & strCode & ",'" & EscQ(strRepairable) & "','" & EscQ(strEntity) & "');"
I think using recordset to add new record will somehow make you worry free about SQL Syntax getting wrong because of special characters e.g. single or double quotes. You can try add a function:
Function insrt_item(rstXL as DAO.Recordset, tbl_dest as String) ' set tbl_dest to ExcelFile or ExcelFileCombined since they are same fields anyway
With currentdb.OpenRecordSet(tbl_dest)
.AddNew
!PN = rstXL!F1
!Description = rstXL!F2
'.. add more fields here
.Update
.Close
End With
End Function