Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fetch data from XML file to Excel sheet using VBA

Tags:

xml

excel

vba

I used the following code to fetch data from XML to Excel. But the problem is, the results are opened in a new workbook "Book1". But I want to get the results in a specific worksheet in the same Excel where I have this macro.
Please note that I don't want to create schema in the code, as the schema changes for all the XMLs. Below mentioned code does not need schema to be specified. It can dump the results in new Excel sheet with the proper column names. So, Please let me know how can I get the results in the sheet2 in the same workbook?

Sub ImportXMLtoList()
 Dim strTargetFile As String
 Application.DisplayAlerts = False
 strTargetFile = "C:\example.xml"
 Workbooks.OpenXML Filename:=strTargetFile, LoadOption:=xlXmlLoadImportToList
 Application.DisplayAlerts = True

End Sub
like image 963
tester Avatar asked Nov 29 '12 06:11

tester


1 Answers

Sub ImportXMLtoList()
Dim strTargetFile As String
Dim wb as Workbook

     Application.Screenupdating = False
     Application.DisplayAlerts = False
     strTargetFile = "C:\example.xml"
     Set wb = Workbooks.OpenXML(Filename:=strTargetFile, LoadOption:=xlXmlLoadImportToList)
     Application.DisplayAlerts = True

     wb.Sheets(1).UsedRange.Copy ThisWorkbook.Sheets("Sheet2").Range("A1")
     wb.Close False
     Application.Screenupdating = True


End Sub
like image 107
Tim Williams Avatar answered Sep 28 '22 05:09

Tim Williams