使用VBA在Excel中重复使用单个XML

时间:2015-05-07 08:13:11

标签: excel vba excel-vba

我起诉我在网上找到的下面的宏,用于将数据从XML提取到Excel。

Sub ListFiles()
'LISTFILES AND LISTMYFILES MODIFIED FROM

'--------------------------------------------------------------------
'DECLARE AND SET VARIABLEs
Dim ShellApplication As Object
Set ShellApplication = CreateObject("Shell.Application").BrowseForFolder(0, "Please choose a folder", 0, OpenAt)
Path = ShellApplication.self.Path
Set ShellApplication = Nothing
[a3] = "XML"
[b3] = "Files"
'--------------------------------------------------------------------
'DEFAULT PATH FROM HIDDEN SHEET
Call ListMyFiles(Path, True)
End Sub

Sub ListMyFiles(mySourcePath, IncludeSubfolders)
    Set MyObject = New Scripting.FileSystemObject
    Set mySource = MyObject.GetFolder(mySourcePath)
    'With SearchXML
    Application.ScreenUpdating = False

    '--------------------------------------------------------------------
    'FIND XML FILES ONLY, APPLY SEARCH CRIERIA, DISPLAY MATCHES ONLY
    For Each myfile In mySource.Files
        If Right(myfile.Name, 3) = "XML" Or Right(myfile.Name, 3) = "xml" Then 'IS XML?
            LastRow = ActiveSheet.Cells(Rows.Count, 2).End(xlUp).Row

            '-------------------------------------------------------------
            'IMPORT XML FILE
            ActiveWorkbook.XmlImport URL:=mySource & "\" & myfile.Name, _
                ImportMap:=Nothing, Overwrite:=True, Destination:=Range("$A$" & LastRow + 1)
            '------------------------------------------------------------
            'DELETE MAPS
            maps = ActiveWorkbook.XmlMaps.Count
            For I = 1 To maps
                ActiveWorkbook.XmlMaps(1).Delete
            Next I
        End If
    Next
    If IncludeSubfolders Then 'SEARCH SUBFOLDERS FOR SAME CRITERIA
        For Each MySubFolder In mySource.SubFolders
            Call ListMyFiles(MySubFolder.Path, True)
        Next
    End If
    'End With
    Application.ScreenUpdating = True
End Sub

Public Sub ClearSheet()
    Cells.Select
    Selection.ClearContents
    [a1].Select
End Sub

但是,它为一些XML生成了多行,但我想为单个XML生成一行。

1 个答案:

答案 0 :(得分:0)

它可能取决于您导入的XML,但有一部分可能需要更正:

maps = ActiveWorkbook.XmlMaps.Count
For I = 1 To maps
    ActiveWorkbook.XmlMaps(1).Delete
Next I

您应该通过添加Step -1

向后浏览
maps = ActiveWorkbook.XmlMaps.Count
For i = 1 To maps Step -1
    ActiveWorkbook.XmlMaps(i).Delete
Next i

希望有所帮助! ;)