循环浏览指定文件夹中的文件并将其导入Excel

时间:2014-03-06 18:11:26

标签: vba excel-vba excel

我正在尝试找到一种方法让Excel循环浏览各种HTML文件并一次导入一个,在移动到下一个文件之前以指定的方式格式化每个文件。这些文件都在FOLDER2中。我怎样才能修改它,不仅要考虑文件,还要考虑文件1 .... n?我遇到的一个直接问题是我收到“运行时错误'1004':Microsoft Excel无法打开或读取此查询文件。”我怀疑这是因为它是HTML而不是XML。当我手动告诉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

更新

我正在尝试修改以下代码,以便我可以简单地选择文件夹并让它以这种方式运行。这是一种合理的方法吗?

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

1 个答案:

答案 0 :(得分:2)

您可以使用FileSystemObject(需要添加对Microsoft Scripting Runtime的引用)来遍历文件夹的内容:

sub loopThroughFolder(folderPath as string)

dim fso as new FileSystemObject
dim fileObj as file

for each fileObj in fso.GetFolder(folderPath).Files
 if filenameFitsCriteria(fileObj.name) then
  importFile(fileObj.Path)
next

end sub

有关选择文件夹的界面,您可以查看:

Application.FileDialog(msoFileDialogFolderPicker)