I have a huge amount of data in Excel format and want to export into a SQL Server table with a faster way than using vba code, though row by row taking lot of time consuming. I found another vba code to upload faster way, however where ever there is a blank cell, it is showing as zero(0) in SQL Server tables only for float datatype as used array to bulk upload.
I have to export cell values as it is available in the Excel sheet. for example, if cell value blank means blank has to be uploaded in SQL Server under float/int datatype.
There is no option for BULK INSERT command as I am using different servers.
Please help.
On Error GoTo 0
cmd.CommandType = 1 ' adCmdText
Dim rst As Object
Set rst = CreateObject("ADODB.Recordset")
table = Range("Table") 'This should be same as the database table name.
With rst
Set .ActiveConnection = con
.Source = "SELECT * FROM " & table
.CursorLocation = 3 ' adUseClient
.LockType = 4 ' adLockBatchOptimistic
.CursorType = 0 ' adOpenForwardOnly
.Open
Dim tableFields(200) As Integer
Dim rangeFields(200) As Integer
Dim exportFieldsCount As Integer
exportFieldsCount = 0
Dim col As Integer
Dim index As Integer
index = 1
For col = 1 To .Fields.Count
exportFieldsCount = exportFieldsCount + 1
tableFields(exportFieldsCount) = col
rangeFields(exportFieldsCount) = index
index = index + 1
Next
If exportFieldsCount = 0 Then
ExportRangeToSQL = 1
'GoTo ConnectionEnd
End If
endRow = ThisWorkbook.Sheets("Sheetname").Range("A1048576").End(xlUp).row 'LastRow with the data.
arr = ThisWorkbook.Sheets("Sheetname").Range("A1:AA" & endRow).Value 'This range selection column count should be same as database table column count.
MsgBox ("Exporting " & endRow - 1 & " records from excel to database.")
rowCount = UBound(arr, 1)
Dim val As Variant
For row = 2 To rowCount
.AddNew
For col = 1 To exportFieldsCount
val = arr(row, rangeFields(col))
.Fields(tableFields(col - 1)) = val
On Error GoTo Error:
Next
Next
MsgBox ("Export to SQL table process started!")
.UpdateBatch
End With
Thanks,