Hi guys,
I am trying to write some VBA code that will read in 2 columns from an excel table, into one access table using the following code:
Code:
Sub getRange()
Dim xlObject As Object
Set xlObject = GetObject(Class:="Excel.Application")
Dim wrkbk As Workbook
Set wrkbk = xlObject.Workbooks("Book1.xlsx")
Dim wrs As Worksheet
Set wrs = wrkbk.Sheets("Sheet 1")
Dim rng As Range
Set rng = wrs.Range("alphabet") 'name of the first range
Dim RANGE_NAME As String
RANGE_NAME = Split(rng.Name, "!")(1)
RANGE_NAME = Replace(RANGE_NAME, "$", "") 'remove the dollar signs to be able to use the variable in the Docmd.transferspreadsheet function
Set rng = wrs.Range("numbers") 'name of the second range
Dim RANGE_NAME2 As String
RANGE_NAME2 = Split(rng.Name, "!")(1)
RANGE_NAME2 = Replace(RANGE_NAME2, "$", "")
Const FILE_PATH As String = "Q:\Fred\Book1.xlsx"
Const TABLE_NAME As String = "Caps"
DoCmd.TransferSpreadsheet _
TransferType:=acImport, _
SpreadsheetType:=acSpreadsheetTypeExcel9, _
TableName:=TABLE_NAME, _
FileName:=FILE_PATH, _
HasFieldNames:=False, _
Range:="Sheet 1!" & RANGE_NAME _
DoCmd.TransferSpreadsheet _
TransferType:=acImport, _
SpreadsheetType:=acSpreadsheetTypeExcel9, _
TableName:=TABLE_NAME, _
FileName:=FILE_PATH, _
HasFieldNames:=False, _
Range:="Sheet 1!" & RANGE_NAME2 _
End Sub
I am reading in the columns based on range names I will have in advance.
My problem is that using the above code, the 2 columns are imported from excel successfully, but they are both imported into the same column. I thought if I used Docmd.transferspreadsheet twice then both pieces of data would be imported into the same table but in different columns.
Any advice on what I can do?
Thanks