I want to create a "generic" way of uploading data to a SQL Server database via Excel upload. In my Excel file I have two sheets - one with data (WS_data) and one with the database table design (WS_Table_Design) (e.g. rows of column names).
It is been a while since I coded VBA, but this used to work (I think?) - what am I thinking wrong here?
Errors comes when I want to "post" the values into the database through .Fields([Column]).Value
Function NullCheck(x)
On Error Resume Next
If x = "" Then
NullCheck = Null
Else
NullCheck = x
End If
End Function
Sub Upload_To_DB()
Dim WS_Data, WS_Table_Design As Worksheet
Dim Curent_Row, Curren_Column, Max_Datarows, i, j As Integer
Dim Array_Table_Design()
Set WS_Data = Worksheets("Data")
Set WS_Table_Design = Worksheets("DB_Table_Design")
'List Columns from Table design in array
ReDim Array_Table_Design(0 To 0)
Current_Row = 1
i = 0
Do While WS_Table_Design.Cells(Current_Row, 1).Value <> ""
If WS_Table_Design.Cells(Current_Row, 1).Value > 0 Then
ReDim Preserve Array_Table_Design(0 To i)
Array_Table_Design(i) = WS_Table_Design.Cells(Current_Row, 1).Value
i = i + 1
End If
Current_Row = Current_Row + 1
Loop
'End List Columns
'Find number of rows to upload
Current_Row = 2 'Row where data starts
Max_Datarows = 0
Do While WS_Data.Cells(Current_Row, 1).Value <> ""
Max_Datarows = Max_Datarows + 1
Current_Row = Current_Row + 1
Loop
'End find number of rows to upload
'Upload data according to Table design and Data sheet
Dim con As ADODB.Connection
Dim rs As ADODB.Recordset
Dim sqlstring As String
Set con = New ADODB.Connection
con.Open "Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=True;Initial Catalog=Datawarehouse;Data Source=server3"
Set rs = New ADODB.Recordset
rs.Open "select * from FactGL", con, adOpenStatic, adLockOptimistic
Current_Row = 2
Current_Column = 1
i = 0
j = 0
For j = 0 To 5 'Max_Datarows
rs.AddNew
For i = 0 To UBound(Array_Table_Design)
'Error comes here - why can't I add data to the database Table column defined in "Array_Table_Design?
rs.Fields("Array_Table_Design(i)").Value = NullCheck(WS_Data.Cells(Current_Row, i + 1).Value)
i = i + 1
Next i
rs.Update
Current_Row = Current_Row + 1
Next j
End Sub