I am trying to add a 3 column Table to a closed Excel File which has no Header rows
Source Data is on Sheet1 from Cells A1:C20 - Named as Data
Eg
CLIENT REGION AMT
ABB NORTH 123
CGL SOUTH 145
etc
The Closed File is Called DB.xls and has a sheet called DB_CUST, located in
D:\DATA\DB.xls
There is no data in the closed file DB.xls -* Not even header rows*
The code below adds the data to DB.xls if there are header rows but does not
work if the header rows are not there.
What changes must I make.... other than HDR = NO. Just by Changing the
HRD=No gives me an error ?
Do I have to change the cursor type ? or include a addnew / movenext
statement in the recordset.....Please help
The below code works if I have headers row in place in the Destination file, howerver it errors out if the destination table is blank
Sub Add_to_Blank_File()
Dim cnt As ADODB.Connection
Dim rst As ADODB.Recordset
Dim wbSource As Workbook
Dim wsSheet As Worksheet
Dim rnSource As Range
Dim stConn As String, stSQL As String, stWbtarget As String
Dim vaSource As Variant
Dim i As Long, j As Long, EndColoum As Long
Set wbSource = ThisWorkbook
Set wsSheet = Sheet1
stWbtarget = Sheet2.Range("VBA_FP") & "\" & Sheet2.Range("VBA_FN")
' or hardcoded sbWbtarget = D:\DATA\Db.xls
With wsSheet
Set rnSource = .Range("Data")
End With
Set cnt = New ADODB.Connection
Set rst = New ADODB.Recordset
stConn = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=" & stWbtarget & ";" & _
"Extended Properties='Excel 8.0;HDR=Yes';"
' I tried chaning Yes to No ….doesnt work
vaSource = rnSource.Value
cnt.Open stConn
stSQL = "SELECT * FROM [DB_CUST$A1:IV65536]"
With rst
.CursorLocation = adUseClient
.Open stSQL, cnt, adOpenForwardOnly, adLockOptimistic, adCmdText
End With
' Do I need to change the cursor type..????
For i = LBound(vaSource) To UBound(vaSource) - 1
With rst
.AddNew
EndColoum = Cells.Find("*", After:=Range("IV65536"),
searchorder:=xlByColumns, SearchDirection:=xlPrevious).Column
For j = 1 To EndColoum
rst(j - 1).Value = vaSource(i + 1, j)
Next j
.Update
End With
Next i
rst.Close
cnt.Close
Set rst = Nothing
Set cnt = Nothing
End Sub