简体   繁体   中英

Rows are repeating for a single XML in Excel using VBA

I am suing the below macro that I found on the net to extract the data from XML to 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

However, it is generating multiple rows for some XMLs, but I want a single row for a single XML.

It may depend on the XML that you import, but there is a part that may need correction :

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

You should go through it backward, by adding Step -1

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

Hope that helped! ;)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM