我想要找到一種方法讓Excel循環訪問各種HTML文件並一次導入一個文件,並以指定方式格式化每個文件,然後再移至下一個文件。這些文件都在FOLDER2中。我如何修改這個來解釋不僅僅是FILE,而是FILE 1 .... n?我遇到的一個即時問題是,我收到「運行時錯誤'1004':Microsoft Excel無法打開或讀取此查詢文件。」我懷疑這是因爲它是HTML而不是XML。當我手動告訴Excel選擇所有文件時,沒有問題,但是宏可能沒有這樣做?通過指定文件夾中的文件循環並將它們導入到Excel
With ActiveSheet.QueryTables.Add(Connection:= _
"FINDER;file:///C:/Users/FOLDER1/FOLDER2/FILE", Destination:= _
Range("$A$1"))
.CommandType = 0
.Name = "FILE"
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.BackgroundQuery = True
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.WebSelectionType = xlEntirePage
.WebFormatting = xlWebFormattingNone
.WebPreFormattedTextToColumns = True
.WebConsecutiveDelimitersAsOne = True
.WebSingleBlockTextImport = False
.WebDisableDateRecognition = False
.WebDisableRedirections = False
.Refresh BackgroundQuery:=False
End With
End Sub
UPDATE:
我想修改下面的代碼,這樣我可以簡單地選擇文件夾,並把它通過這種方式運行。這是一個合理的方法嗎?
Sub ImportXMLData()
Application.ScreenUpdating = False
Dim strFolder As String, strFile As String
Dim xlWkBk As Workbook, xmlFile As Workbook, LastRow As Long
strFolder = GetFolder
If strFolder = "" Then Exit Sub
strFile = Dir(strFolder & "\*.html", vbNormal)
Set xlWkBk = ThisWorkbook
While strFile <> ""
LastRow = xlWkBk.Sheets(1).Cells.SpecialCells(xlCellTypeLastCell).Row + 1
Set xmlFile = Workbooks.OpenXML(Filename:=strFolder & "\" & strFile)
xmlFile.Sheets(1).UsedRange.Copy
xlWkBk.Sheets(1).Cells(LastRow, 1).Paste
xmlFile.Close SaveChanges:=False
strFile = Dir()
Wend
Set xmlFile = Nothing: Set xlWkBk = Nothing
Application.ScreenUpdating = True
End Sub
Function GetFolder() As String
Dim oFolder As Object
GetFolder = ""
Set oFolder = CreateObject("Shell.Application").BrowseForFolder(0, "Choose a folder", 0)
If (Not oFolder Is Nothing) Then GetFolder = oFolder.Items.Item.Path
Set oFolder = Nothing
End Function
也許** [這](http://stackoverflow.com/a/21555957/2687063)**可以幫助。 –