Open xml file as table in vbs

CaptainGravyBum

Board Regular
Joined
Dec 1, 2023
Messages
100
Office Version
  1. 365
Platform
  1. Windows
Hi all,
I need to create a vbscript to open an xml file as an xml table into the existing workbook that is open.
Whenever I try to use the import data function, I can't get any data to show, but the file - open - xml file works fine as long as I select xml table, although it tends to open into a new sheet rather than the one i'm working on.
Ideally I'd have something that just asks the user to browse for the file and it shoves the data into cell a1 on the existing sheet.
Hope you can help.
 
Nevermind, I found this and it is working fine.

Sub ImportXMLAsTable()
Dim ws As Worksheet
Dim xmlFile As String
Dim xmlMap As XmlMap
Dim fd As FileDialog

' Set the active worksheet where data should be inserted
Set ws = ActiveSheet

' Open file picker dialog to select XML file
Set fd = Application.FileDialog(msoFileDialogFilePicker)
With fd
.Title = "Select XML File"
.Filters.Clear
.Filters.Add "XML Files", "*.xml"
.AllowMultiSelect = False
If .Show = -1 Then
xmlFile = .SelectedItems(1)
Else
Exit Sub ' If no file is selected, exit the macro
End If
End With

' Remove any existing XML maps to avoid conflicts
On Error Resume Next
For Each xmlMap In ThisWorkbook.XmlMaps
ThisWorkbook.XmlMaps.Remove xmlMap
Next xmlMap
On Error GoTo 0

' Add XML map to the workbook
Set xmlMap = ThisWorkbook.XmlMaps.Add(xmlFile)

' Check if the XML map was added successfully
If xmlMap Is Nothing Then
MsgBox "Failed to load XML. Ensure it's a valid XML file.", vbExclamation, "Error"
Exit Sub
End If

' Import the XML data into the active sheet at A1
ws.Range("A1").Select
ThisWorkbook.XmlImport xmlFile, xmlMap, True, ws.Range("A1")

MsgBox "XML imported successfully!", vbInformation, "Success"

End Sub
 
Upvote 0
Solution

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top