我目前正在創建一個腳本,它將將指定文件夾中的所有Excel表單導入到Microsoft Access中的唯一表中。現在,這個過程應該每月或每兩個月進行一次,這些excel表單上的標題經常變化。我試圖使用DoCmd.Transferspreadsheet方法,但我遇到的問題是這些字段與目標表不匹配。現在,我不能只使用適當的字段名稱來創建表格,然後導入到表格中,因爲正如我所說,excel文件的標題經常變化。將Excel導入到Access中,動態獲取列標題
我想要一種方法來導入一個Excel表格到一個新表格中,並且該表格應該自動採用Excel表格的字段,而不管它們是什麼。因此,基本上每次我導入時,都應該使用適當的字段創建一個新表。
我唯一的解決方法是創建一個新的表格,每次我導入並循環查找excel文件的第一行以查找字段的名稱,然後在創建表格時使用該表格。
但這是一個混亂的解決方法。我知道可以使用微軟訪問用戶界面導入到全新的表格中。它需要點擊幾下,然後它的一切都很好。
我想要一個編程解決方案。
Function loadData()
Dim strPathFile As String, strFile As String, strPath As String
Dim strTable As String
Dim blnHasFieldNames As Boolean
' Change this next line to True if the first row in EXCEL worksheet
' has field names
blnHasFieldNames = True
' Replace C:\Documents\ with the real path to the folder that
' contains the EXCEL files
strPath = "C:\Bdz outputs\"
' Replace tablename with the real name of the table into which
' the data are to be imported
strFile = Dir(strPath & "*.xlsx")
strTable = Left(strFile, 8)
strPathFile = strPath & strFile
'Debug.Print (createTable("hello", "asdasd"))
Do While Len(strFile) > 0
strPathFile = strPath & strFile
DoCmd.TransferSpreadsheet acImport, acSpreadsheetTypeExcel12, "Table1", strPathFile, False
' Uncomment out the next code step if you want to delete the
' EXCEL file after it's been imported
'Kill strPathFile
strFile = Dir()
Loop
End Function
如果您無法通過TransferSpreadsheet找到一種方法,則可以編寫代碼來打開並閱讀Excel電子表格。可以通過編程方式更改標題名稱,或者另一個選項,如果excel列值類型始終與訪問列類型匹配,則可以保留訪問名稱,並只需在Excel標題後面逐行插入。 – PKatona
我可能不理解,但如果您在[TransferSpreadsheet](https://msdn.microsoft.com/en-us/library/office/ff844793.aspx)的表參數中指定一個不存在的表名並指定* True *用於列標題,MS Access用Excel文件的標題精確地導入電子表格。 – Parfait