我正在使用 MS Access 從檔案夾中匯入大量文本檔案。每個文本檔案都具有相同的結構和一個包含有用資料的大標題。我將每個文本檔案作為空格分隔檔案匯入到臨時表中,并使用一系列查詢來收集相關資訊并將所有內容附加到主表中。我正在嘗試自動化此程序,并創建了一個宏來運行所有查詢。我正在使用以下 VBA 嘗試遍歷檔案夾中的每個檔案,但遇到了一些問題。我似乎無法獲得下一個檔案匯入來替換每次迭代的臨時表的內容。我是 VBA 新手,所以任何提示或技巧將不勝感激!
Public Sub LoopThroughFiles()
Dim strFileName As String
Dim intNumberOfFiles As Integer
intNumberOfFiles = 0
strFileName = Dir("My_File_Path\*", vbNormal)
Do Until strFileName = ""
intNumberOfFiles = intNumberOfFiles 1
strFileName = Dir()
DoCmd.TransferText acImportDelim, My_Import_Spec, "My_Staging_Table", Dir(), False
DoCmd.RunMacro ("RunMacros")
Loop
End Sub
編輯 1:您好,感謝您到目前為止的出色回答!我已經實作了以下代碼,但我在 DoCmd.TransferText 行上不斷收到相同的錯誤:“運行時錯誤 3027
無法更新。資料庫或物件是只讀的。”
根據您的建議,這是我正在使用的代碼:
Private Sub Loopthroughfiles()
Const SRC_PATH As String = "FilePath" 'for example
Dim strFileName As String
Dim NumberOfFiles As Long 'prefer Long to Integer
strFileName = Dir(SRC_PATH & "*.txt", vbNormal)
NumberOfFiles = 0
Do Until strFileName = "FilePath\LastFileName.txt"
NumberOfFiles = NumberOfFiles 1
DoCmd.TransferText acImportDelim, MyImportSpec, "MyStagingTable", _
SRC_PATH & strFileName, False
DoCmd.RunMacro "RunMacros"
strFileName = Dir() 'next file
CurrentDb.Execute "DELETE * FROM [MyStagingTable]", dbFailOnError
Loop
MsgBox NumberOfFiles & " files imported"
End Sub
uj5u.com熱心網友回復:
我想也許這樣的事情應該有效:
Const SRC_PATH As String = "C:\Testing\" 'for example
Dim strFileName As String
Dim NumberOfFiles As Long 'prefer Long to Integer
NumberOfFiles = 0
strFileName = Dir(SRC_PATH & "*.txt", vbNormal)
Do Until strFileName = ""
NumberOfFiles = NumberOfFiles 1
DoCmd.TransferText acImportDelim, My_Import_Spec, "My_Staging_Table", _
SRC_PATH & strFileName, False
DoCmd.RunMacro "RunMacros"
strFileName = Dir() 'next file
Loop
MsgBox NumberOfFiles & " files imported"
uj5u.com熱心網友回復:
這是你想要的嗎?
Private Sub Command0_Click()
Dim strPathFile As String, strFile As String, strPath As String
Dim strTable As String
Dim blnHasFieldNames As Boolean
blnHasFieldNames = True
strPath = "C:\Users\ryans\OneDrive\Desktop\test\"
strTable = "Table1"
strFile = Dir(strPath & "*.txt")
Do While Len(strFile) > 0
strPathFile = strPath & strFile
DoCmd.TransferText acImportDelim, _
TableName:="Test1", _
FileName:=strPath & strFile, _
HasFieldNames:=True
strFile = Dir()
Loop
End Sub
如果沒有,請回帖提供更多詳細資訊。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/391125.html
