Skip to content

Instantly share code, notes, and snippets.

@stevesohcot
Created July 31, 2021 01:38
Show Gist options
  • Select an option

  • Save stevesohcot/7f909d933028052a63047270619f32ad to your computer and use it in GitHub Desktop.

Select an option

Save stevesohcot/7f909d933028052a63047270619f32ad to your computer and use it in GitHub Desktop.
VBA Import data from Excel to Database
Public Function ImportData(sheet As String)
Dim i As Long
Dim strSQL As String
Dim totalRows As Long
totalRows = HowManyRows(sheet)
strInsertHeader = GetInsertHeader()
Dim strIndividualRows As String
strIndividualRows = ""
For i = 2 To totalRows
strIndividualRows = strIndividualRows & getSQLForSingleRow(sheet, i)
' add comma at the end no matter what; remove last one after
strIndividualRows = strIndividualRows & ","
'Worksheets("Instructions").Range("I2").FormulaR1C1 = "Rows read in: " & i
' insert into the database before it gets too big
If (i Mod 500) = 0 Then
strSQL = strInsertHeader & " VALUES " & strIndividualRows
strSQL = RemoveLastCharacterIfComma(strSQL)
Call RunSQL(strDbConn, strSQL)
strIndividualRows = ""
'Debug.Print "in the middle of importing " & i
End If
Next
' insert in the last batch
strSQL = strInsertHeader & " VALUES " & strIndividualRows
strSQL = RemoveLastCharacterIfComma(strSQL)
Call RunSQL(strDbConn, strSQL)
strIndividualRows = ""
'Debug.Print "last row " & i
Range("A1").Select
' Complete: clear out the status
' Worksheets("Instructions").Range("I1").Formula2R1C1 = ""
' Worksheets("Instructions").Range("I2").Formula2R1C1 = ""
'MsgBox sheet + " data imported"
End Function
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment