Как открыть xml файл в excel vba

 

JeyCi

Пользователь

Сообщений: 3357
Регистрация: 27.11.2013

способ 1 — ссылка на картинку не вставляется —

линк


способ 2 —

uvSelectFromXML

способ 3 — макросом — ищите на форуме запросы к TXT, изменяйте на XML (коды запросов по способ 1 на vba)
способ 4 — разобрать

XML IN 20 MINUTES!

 и адаптировать для vba
способ 5 —

Надстройка Активные таблицы

— не тестировала, но, полагаю, вместо TEXT, используя XML, — можно попробовать — если файлы в сети должно работать

Изменено: JeyCi22.03.2017 09:46:51

чтобы не гадать на кофейной гуще, кто вам отвечает и после этого не совершать кучу ошибок — обратитесь к собеседнику на ВЫ — ответ на ваш вопрос получите — а остальное вас не касается (п.п.п. на форумах)

0 / 0 / 0

Регистрация: 27.02.2012

Сообщений: 21

1

15.01.2014, 07:13. Показов 25251. Ответов 8


Студворк — интернет-сервис помощи студентам

Добрый день. Есть такая задача:

  1. Есть xml файл в котором есть перечень сотрудников. Нужно циклом из этого файла фамилию каждого сотрудника выгрузить в отдельную ячейку в екселе. Как сделать это макросом
  2. Как сделать цикл, чтобы он сканировал xml файл до самой последней строки, так как не известно сколько сотрудников будет в нем указано.

Пример файла во вложении



0



Surrogate

Ушел с CyberForum совсем!

873 / 182 / 25

Регистрация: 04.05.2011

Сообщений: 1,020

Записей в блоге: 110

15.01.2014, 11:13

2

Цитата
Сообщение от drzod
Посмотреть сообщение

Есть xml файл в котором есть перечень сотрудников. Нужно циклом из этого файла фамилию каждого сотрудника выгрузить в отдельную ячейку в екселе. Как сделать это макросом

файл xml отрывается ровно также как книги экселя

Visual Basic
1
2
dim wb as workbook
Set wb = Workbooks.Open("c:9070481out9070481out.xml")

В приложенном файле фамилии хранятся в 10-ом столбце, их значения в целевой файл можно считывать так

Visual Basic
1
wb.Sheets(1).Cells(3, 10).Value

Цитата
Сообщение от drzod
Посмотреть сообщение

Как сделать цикл, чтобы он сканировал xml файл до самой последней строки, так как не известно сколько сотрудников будет в нем указано.

тело таблицы начинается с третьей строки, для определения общего количества строк можно использовать цикл

Visual Basic
1
For x = 3 To wb.Sheets(1).UsedRange.Rows.Count

Добавлено через 2 минуты
drzod, а строчку которая будет вытягивать значения из xml в целевую книгу экселя уже за тобой



1



0 / 0 / 0

Регистрация: 27.02.2012

Сообщений: 21

15.01.2014, 11:57

 [ТС]

3

А представьте около 10000 cm файлов. Надо каждый так загружать? ))) хах, решение нашел. Все спасибо за помощь



0



Ушел с CyberForum совсем!

873 / 182 / 25

Регистрация: 04.05.2011

Сообщений: 1,020

Записей в блоге: 110

15.01.2014, 12:03

4

Цитата
Сообщение от drzod
Посмотреть сообщение

А представьте около 10000 cm файлов. Надо каждый так загружать? )))

10000 cm ? это как

Цитата
Сообщение от drzod
Посмотреть сообщение

хах, решение нашел

в чем секрет, если не секрет ?



0



0 / 0 / 0

Регистрация: 27.02.2012

Сообщений: 21

15.01.2014, 12:16

 [ТС]

5

В вашем решении я как понимаю каждую xmlку макрос открывает и это визуально видно. Думаю это может плохо сказаться на производительности.

Вот так подсказали решение. Я потом пот себя переделал. Сделал цикл, чтобы выдергивать имя файла из ячейки, он «открывался» там искались определенные параметры. В случае их обнаружения выполнялось условие

А 10000 строк — ну хз, такой объем данных ))

Добавлено через 45 секунд
тут

Добавлено через 1 минуту
Короче домой приду, кину ссылку. С телефона не удобно ))



0



Ушел с CyberForum совсем!

873 / 182 / 25

Регистрация: 04.05.2011

Сообщений: 1,020

Записей в блоге: 110

15.01.2014, 13:15

6

Цитата
Сообщение от drzod
Посмотреть сообщение

В вашем решении я как понимаю каждую xmlку макрос открывает и это визуально видно. Думаю это может плохо сказаться на производительности.

в моем решении xml открывается один раз и считывает все строки будь их хоть 100500. Или таких xml со списками фамилий не одна ?



0



0 / 0 / 0

Регистрация: 27.02.2012

Сообщений: 21

15.01.2014, 13:28

 [ТС]

7

Их Оооочень много

Добавлено через 1 минуту
В любом случае спасибо вам за помощь. Вы единственный откликнулись



0



Surrogate

Ушел с CyberForum совсем!

873 / 182 / 25

Регистрация: 04.05.2011

Сообщений: 1,020

Записей в блоге: 110

15.01.2014, 15:00

8

Цитата
Сообщение от drzod
Посмотреть сообщение

Их Оооочень много

вчера в этой ветке помогали человеку исправить 150 книг эксель

Добавлено через 24 минуты
если все xml в одной папке то код будет такой

Visual Basic
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
Sub drzod()
Dim TheFolder, TheFiles, AFile
Set FSO = CreateObject("Scripting.FileSystemObject")
Set TheFolder = FSO.GetFolder("c:9070481out") ' папка где лежат все xml
Set TheFiles = TheFolder.Files
For Each AFile In TheFiles
ReadXML (AFile)
Next
End Sub
Sub ReadXML(af As String)
Dim xml_doc As New DOMDocument
Dim nde_test As IXMLDOMElement
xml_doc.Load af
For Each nde_test In xml_doc.SelectNodes("//Сотрудник")
  Debug.Print nde_test.SelectSingleNode("Фамилия").Text
Next
End Sub

Добавлено через 34 минуты

Цитата
Сообщение от drzod
Посмотреть сообщение

В любом случае спасибо вам за помощь. Вы единственный откликнулись

Не единственный, ведь код с DOMDocument тебе на другом форуме присоветовали



0



72 / 0 / 0

Регистрация: 19.06.2014

Сообщений: 68

16.03.2016, 11:32

9

Добрый день.
А как быть, если файл такого вида, меняю и ничего не получается(



0



I want program my button with this features:

open and select a xml file then write in «table2» the metric name id M1-M10 with the belonging values.

I was successful to open and select a xml file:

Private Sub btn_load_xml_Click()
'-----------Open file---------------------------
Dim Filter As String, Title As String
Dim FilterIndex As Integer
Dim Filename As Variant

' File filters
Filter = "XML Files (*.xml),*.xml"
' Default Filter to *.*

FilterIndex = 3
' Set Dialog Caption
Title = "Select a File to Open"

' Select Start Drive & Path
ChDrive ("C")
ChDir ("C:")
With Application
    ' Set File Name to selected File
    Filename = .GetOpenFilename(Filter, FilterIndex, Title)
    ' Reset Start Drive/Path
    ChDrive (Left(.DefaultFilePath, 1))
    ChDir (.DefaultFilePath)
End With

' Exit on Cancel
If Filename = False Then
    Exit Sub
End If

' Open File   
MsgBox Filename, vbInformation, "File Opened" ' This can be removed
'------------- Load XML in table2------------------

'------------- END Load XML in table2------------------
End Sub

But how can I load the XML file and work with it ?

Here is my XML structure

<?xml version="1.0" encoding="UTF-8" ?>

<sourcemonitor_metrics>
  <project version="3.3">
    <project_name>metric_auswertung</project_name>
    <project_directory>C:UsersSULASDesktopMetric_auswertung</project_directory>
    <project_language>C</project_language>

    <ignore_headers_footers>false</ignore_headers_footers>
    <export_raw_numbers>false</export_raw_numbers>
    <metric_names name_count="13">
      <metric_name id="M0" type="number">Lines</metric_name>
      <metric_name id="M1" type="number">Statements</metric_name>
      <metric_name id="M2" type="percent" divisor="M1">Percent Branch Statements</metric_name>
      <metric_name id="M3" type="percent" divisor="M0">Percent Lines with Comments</metric_name>
      <metric_name id="M4" type="number">Functions</metric_name>
      <metric_name id="M5" type="average" divisor="M4">Average Statements per Function</metric_name>
      <metric_name id="M6" type="string">Line Number of Most Complex Function</metric_name>
      <metric_name id="M7" type="string">Name of Most Complex Function</metric_name>
      <metric_name id="M8" type="maximum">Complexity of Most Complex Function</metric_name>
      <metric_name id="M9" type="string">Line Number of Deepest Block</metric_name>
      <metric_name id="M10" type="maximum">Maximum Block Depth</metric_name>
      <metric_name id="M11" type="average" values="block_depths">Average Block Depth</metric_name>
      <metric_name id="M12" type="average">Average Complexity</metric_name>
    </metric_names>
    <checkpoints checkpoint_count="1">
      <checkpoint checkpoint_name="Metric_Auswertung" ignore_blank_lines="false" modified_complexity="true" checkpoint_date="2013-02-25">
        <files file_count="3">
          <file file_name="Mcu - Kopie.c">
            <metrics metric_count="13">
              <metric id="M0">603</metric>
              <metric id="M1">183</metric>
              <metric id="M2">26,2</metric>
              <metric id="M3">23,2</metric>
              <metric id="M4">11</metric>
              <metric id="M5">24,6</metric>
              <metric id="M6">321</metric>
              <metric id="M7">Mcu_GetPllStatus()</metric>
              <metric id="M8">15</metric>
              <metric id="M9">235</metric>
              <metric id="M10">6</metric>
              <metric id="M11">1,97</metric>
              <metric id="M12">6,00</metric>
            </metrics>
          </file>
        </files>
      </checkpoint>
    </checkpoints>
  </project>
</sourcemonitor_metrics>

Convert XML Files to Excel – 5 Methods to Import

To Import XML data to Excel you can use any of these listed methods.

  1. VBA to import XML to Excel
    1. Quick VBA to Convert XML into Excel
    2. VBA to read each nodes in XML
    3. VBA to Import XML from any website
  2. Directly Open XML in Excel.
  3. Data Import to Convert XML to XLSX

Lets review one by one & get free Excel macro code also to do this.

1. VBA Read XML file into Excel

1.1 Quick VBA To Convert XML to Excel

This methods import and open XML file in Excel from local path, but it is slightly different from the previous methods.

This does a plain import in quick way.

Public Sub Convert_XML_To_Excel_From_Local_Path()
    Dim xml_File_Path As String
    Dim wb As Workbook
    
    'Load XML Data into a New Workbook - Code from Officetricks.com
    Application.DisplayAlerts = False
     xml_File_Path = ThisWorkbook.Sheets(1).Cells(2, 1)
     Set wb = Workbooks.OpenXML(Filename:=xml_File_Path)

    'Copy Content from New workbook to current active Worksheet
     wb.Sheets(1).UsedRange.Copy ThisWorkbook.Sheets("Sheet2").Range("A1")
     
     'Close New Workbook & Enable Alerts
     wb.Close False
     Application.DisplayAlerts = True
End Sub

1.2 Advanced method to Read each node in XML file using VBA

This VBA code will import XML to Excel by reading each element or node in it, using object model.

If it is not just an plain import & you want to process each XML node in code, then this is the most preferred method.

Public Sub Convert_XML_To_Excel_Through_VBA()
    'Code from Officetricks.com
    'Add referece from Menu: "Tools -> References -> Microsoft XML Vn.0"
    Dim iRow As Integer, iCol As Integer
    Dim xmlDoc As MSXML2.DOMDocument, xmlRoot As MSXML2.IXMLDOMNode
    Dim xmlNodes As MSXML2.IXMLDOMNode, xmlData As MSXML2.IXMLDOMNode
    Set xmlDoc = New MSXML2.DOMDocument
    
    'Load & Wait till complete XML Data is loaded
    xmlDoc.async = False
    xmlDoc.validateOnParse = False
    xmlDoc.Load ("D:sitemap.xml")
    
    'XML Loaded. Now Read Elements One by One into XML DOM Objects
    Set xmlRoot = xmlDoc.DocumentElement
    Set xmlNodes = xmlRoot.FirstChild
    
    'Read XML Data and Load into Excel Sheet by each Node and Chile Node
    iRow = 0
    For Each xmlNodes In xmlRoot.ChildNodes
        iRow = iRow + 1
        iCol = 0
        
        For Each xmlData In xmlNodes.ChildNodes
            iCol = iCol + 1
            ThisWorkbook.Sheets(2).Cells(1, iCol) = xmlData.BaseName
            ThisWorkbook.Sheets(2).Cells(iRow, iCol) = xmlData.Text
        Next xmlData
    Next xmlNodes
End Sub

Before executing the code above, just change the path of the input file in the line, xmlDoc.Load.

By this method, you will be able to import multiple XML  files into Excel.

1.3 Import XML into Excel using VBA from Website

The above method is used to load data from a local file. Use the below method if you have to import XML data to Excel from a website URL directly.

Public Sub Import_XML_From_URL()
    'Clear & Setup Output Sheet - Code from Officetricks.com
    ThisWorkbook.Sheets(2).Activate
    ThisWorkbook.Sheets(2).Cells.Select
    Selection.ClearContents
    
    'Switch Off Alert Messages while Importing.
    Application.DisplayAlerts = False
    
    'VBA Command To Import XML File from Website to Excel
    ThisWorkbook.XmlImport URL:="XML_File_Download_URL", ImportMap:= _
        Nothing, Overwrite:=True, Destination:=ThisWorkbook.Sheets(2).Range("$A$1")
    
    Application.DisplayAlerts = True
End Sub

All the methods discussed above can be used to automate the process of converting XML to Excel file from a local computer or from a Website URL.

To convert XML file to Excel using menu options, follow these simple steps.

  1. Open a Excel workbook (xls or xlsx).
  2. Click ‘File’ menu & choose ‘Open’ (shortcut – ‘Alt+F+O’).
  3. Browse folder path & choose XML file.
  4. Click ‘Open’ or press ‘Enter’.
  5. Choose ‘As an XML table’ in popup menu & click ‘OK’.
  6. Click ‘OK’ when Excel notify that a schema will be created based on XML source data.

Now, the system will import XML to Excel in active worksheet.

But, wait. We do have more easy methods & even few VBA codes do perform this task.

3. Data Import XML to Excel – Menu Option

To view XML in proper readable format, you can open XML files in Excel using the “Data Import” feature as explained below.

  1. Click ‘Data’ menu & choose ‘From Other Sources’ (shortcut – ‘Alt+A+F+O’)
  2. Select “From XML Data Import”.
  3. Choose XML path and file in ‘Select Data Source’ window.
  4. Excel will notify about schema creation by itself. Click OK.
  5. Choose target cell address to import XML data.
  6. Click ‘OK’.

Usually in manual options, Excel itself will guide you to further steps to import XML to Excel. These option are built in options of Microsoft XML converter.

It is also possible to import data in XML to Excel through macro Code. We have explained 3 different methods in this article to this through VBA.

View XML Maps – Data mapping using Excel

Excel will create a schema by itself once your import XML into Excel. To view the XML maps added to the Excel workbook, follow these steps.

  1. Right click on imported XML table.
  2. Select ‘XML’ in the popup menu & choose “XML Source”.
  3. Sidebar on right hand side will appear with source details.
  4. Edit Map field details in this sidebar.
  5. Click on  ‘XML Maps’ to view list of maps linked.
  6. Rename, Add, Delete, Assign map schema details in this window.

The same option is also available in Developer Tab “Document Panel” from the Excel Menu. Use this option to assign a new schema or map to the imported XML file.

Note: Similar to editing importing XML, you can create a XML file from Excel directly, by saving it in XML format, right from the ‘File’ menu ‘Save As’ Option.

Import Sitemap to Excel

Bloggers, Web Admin, SEO & Marketing people scan through sitemaps from lot of websites to improve the performance of their pages in search engine result pages. They can use the techniques in this page to import Sitemap from a Website and process all the links within that Domain.

We have completed few quick steps about Extensible Markup Language or XML to Excel converter. This file format is used to exchange data between computer applications across Internet, LAN or  apps within same Computer.

This file can be opened in any Internet browsers (Firefox, Chrome, IE, Opera etc.,) or a Text editor directly to view it’s content since it is not a encoded format. But, to view it in a readable format, this article will help more.

Other Reference: Microsoft Answers on Importing XML data

By this, you can create your own Excel XML viewer. We have summarized 2 manual methods & 3 different methods using VBA. Be it on-demand process or automation, this complete guide about converting a XML file to Excel will be a handy quick reference.

Содержание

  1. Метод Workbooks.OpenXML (Excel)
  2. Синтаксис
  3. Параметры
  4. Возвращаемое значение
  5. Пример
  6. Поддержка и обратная связь
  7. Метод Workbook.XmlImport (Excel)
  8. Синтаксис
  9. Параметры
  10. Возвращаемое значение
  11. Замечания
  12. Поддержка и обратная связь
  13. Parsing XML in Microsoft Excel VBA
  14. Importance of an XML Parser
  15. Build XML Parser Using VBA
  16. VBA Macro Import – Read XML File into Excel – 5 Easy Tips
  17. Convert XML Files to Excel – 5 Methods to Import
  18. 1. VBA Read XML file into Excel
  19. 1.1 Quick VBA To Convert XML to Excel
  20. 1.2 Advanced method to Read each node in XML file using VBA
  21. 1.3 Import XML into Excel using VBA from Website
  22. 2. How to Convert XML to Excel?
  23. 3. Data Import XML to Excel – Menu Option
  24. View XML Maps – Data mapping using Excel
  25. Import Sitemap to Excel
  26. Load XML into Excel through VBA
  27. 2 Answers 2

Метод Workbooks.OpenXML (Excel)

Открывает XML-файл данных. Возвращает объект Workbook .

Синтаксис

expression. OpenXML (FileName, Stylesheets, LoadOption)

Выражение Переменная, представляющая объект Workbooks .

Параметры

Имя Обязательный или необязательный Тип данных Описание
FileName Обязательный String Имя открываемого файла.
Stylesheets Необязательный Variant Одно значение или массив значений, указывающий инструкции по обработке таблицы стилей преобразования XSL (XSLT).
LoadOption Необязательный Variant Указывает, как Excel открывает XML-файл данных. Может быть одной из констант XlXmlLoadOption .

Возвращаемое значение

Пример

Следующий код открывает XML-файл данных Customers.xml и отображает содержимое файла в списке XML.

Поддержка и обратная связь

Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь.

Источник

Метод Workbook.XmlImport (Excel)

Импортирует XML-файл данных в текущую книгу.

Синтаксис

expression. XmlImport (URL-адрес, ImportMap, перезапись, назначение)

Выражение Переменная, представляющая объект Workbook .

Параметры

Имя Обязательный или необязательный Тип данных Описание
Url Обязательный String Универсальный указатель ресурсов (URL-адрес) или UNC-путь к XML-файлу данных.
ImportMap Обязательный XmlMap Схема, применяемая при импорте файла. Если данные были импортированы ранее, содержит ссылку на объект XmlMap , содержащий данные.
Overwrite Необязательный Variant Если значение не указано для параметра Destination , этот параметр указывает, следует ли перезаписывать данные, сопоставленные с картой схемы, указанной в параметре ImportMap . Задайте значение True , чтобы перезаписать данные, или False , чтобы добавить новые данные к существующим данным. Значение по умолчанию — True.

Если для параметра Destination задано значение, этот параметр указывает, следует ли перезаписывать существующие данные. Установите значение True , чтобы перезаписать существующие данные, или Значение False , чтобы отменить импорт, если данные будут перезаписаны. Значение по умолчанию — True. Destination Необязательный Variant Указывает диапазон, в котором будет создан список. Используйте только левый верхний угол диапазона.

Возвращаемое значение

Замечания

Этот метод позволяет импортировать данные в книгу из пути к файлу. Excel использует первую найденную сопоставимую карту или, если указан диапазон назначения, Excel автоматически выводит данные.

Не указывайте значение для параметра Destination , если вы хотите импортировать данные в существующее сопоставление.

Следующие условия приводят к возникновению ошибок во время выполнения методом XmlImport :

Указанные XML-данные содержат синтаксические ошибки.

Процесс импорта был отменен, так как указанные данные не могут поместиться на лист.

Если соответствующие карты не найдены и диапазон назначения не указан.

Используйте метод XmlImportXml объекта Workbook для импорта XML-данных, которые ранее были загружены в память.

Поддержка и обратная связь

Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь.

Источник

Parsing XML in Microsoft Excel VBA

This article will teach us how to parse XML files in VBA.

Importance of an XML Parser

As a Microsoft Excel user, it is common that you might receive some data in the form of an XML file. You will have to retrieve the information from the XML file and use it in your sheets or VBA macros according to your requirement.

A way to do this is to treat it as a text file and parse the information. But this is not an elegant way to parse XML files since the information is stored well-structured using tags, and treating it as a text file negates this concept.

Therefore, we will have to make use of an XML Parser. An XML Parser reads the XML file and retrieves the relevant data so it can be used readily.

Build XML Parser Using VBA

We can parse an XML file using VBA and convert the data into our Excel sheet. The method we will be using uses the XML DOM implementation, short for the XML Document Object Model, and this model allows us to represent the XML file as an object we can then manipulate as required.

To start parsing your XML file through VBA, you must perform a simple sequence of steps. These are explained below.

To parse XML through VBA, you need to have MSXML.4.0 or greater on your system.

Add Reference to Microsoft XML

First, you need to add a reference to Microsoft XML, V6.0 in the VBA Editor. This is how it is done:

Open the VBA Editor from the Developer tab in Excel.

In the menu, go to Tools > References.
Scroll down and check Microsoft XML, V6.0 , then click on OK .

Note that the version of Microsoft XML depends on the operating system and Microsoft Office installed on your computer.

Write VBA Code to Load the XML File Into XML DOM

Suppose we have the following XML file:

We can use the following code to parse this XML file through VBA by making an XML DOM object in the following way:

In the code above, we have first created a variable xDoc of the MSXML2.DOMDocument60 type. Here, we have appended 60 at the end because we are using version 6.0 of Microsoft XML , and without the 60 , this code will generate a compile-time error of User-defined type not found .

Next, we have specified that we are working with the xDoc variable using the With statement. The .async property defines permission for asynchronous downloads, and the .validateOnParse property indicates if the parser should validate the XML document.

After that, we use the .Load function to load the specified XML file into the DOM variable. Here, you can change the path and file name to the one on your computer.

The next two lines are for error handling in case the XML file is not loaded properly. To test if the loading has worked, we take one node from the file and specify its name as price .

You should note that the node name is case-sensitive and must be specified according to your XML file. Finally, we display the price using the node.Text property in a message box.

This shows that the loading has worked perfectly fine.

Источник

VBA Macro Import – Read XML File into Excel – 5 Easy Tips

Convert XML Files to Excel – 5 Methods to Import

To Import XML data to Excel you can use any of these listed methods.

Please enable JavaScript

  1. VBA to import XML to Excel
    1. Quick VBA to Convert XML into Excel
    2. VBA to read each nodes in XML
    3. VBA to Import XML from any website
  2. Directly Open XML in Excel.
  3. Data Import to Convert XML to XLSX

Lets review one by one & get free Excel macro code also to do this.

1. VBA Read XML file into Excel

1.1 Quick VBA To Convert XML to Excel

This methods import and open XML file in Excel from local path, but it is slightly different from the previous methods.

This does a plain import in quick way.

1.2 Advanced method to Read each node in XML file using VBA

This VBA code will import XML to Excel by reading each element or node in it, using object model.

If it is not just an plain import & you want to process each XML node in code, then this is the most preferred method.

Before executing the code above, just change the path of the input file in the line, xmlDoc.Load.

By this method, you will be able to import multiple XML files into Excel.

1.3 Import XML into Excel using VBA from Website

The above method is used to load data from a local file. Use the below method if you have to import XML data to Excel from a website URL directly.

All the methods discussed above can be used to automate the process of converting XML to Excel file from a local computer or from a Website URL.

2. How to Convert XML to Excel?

To convert XML file to Excel using menu options, follow these simple steps.

  1. Open a Excel workbook (xls or xlsx).
  2. Click ‘File’ menu & choose ‘Open’ (shortcut – ‘Alt+F+O’).
  3. Browse folder path & choose XML file.
  4. Click ‘Open’ or press ‘Enter’.
  5. Choose ‘As an XML table’ in popup menu & click ‘OK’.
  6. Click ‘OK’ when Excel notify that a schema will be created based on XML source data.

Now, the system will import XML to Excel in active worksheet.

But, wait. We do have more easy methods & even few VBA codes do perform this task.

To view XML in proper readable format, you can open XML files in Excel using the “Data Import” feature as explained below.

  1. Click ‘Data’ menu & choose ‘From Other Sources’ (shortcut – ‘Alt+A+F+O’)
  2. Select “From XML Data Import”.
  3. Choose XML path and file in ‘Select Data Source’ window.
  4. Excel will notify about schema creation by itself. Click OK.
  5. Choose target cell address to import XML data.
  6. Click ‘OK’.

Usually in manual options, Excel itself will guide you to further steps to import XML to Excel. These option are built in options of Microsoft XML converter.

It is also possible to import data in XML to Excel through macro Code. We have explained 3 different methods in this article to this through VBA.

View XML Maps – Data mapping using Excel

Excel will create a schema by itself once your import XML into Excel. To view the XML maps added to the Excel workbook, follow these steps.

  1. Right click on imported XML table.
  2. Select ‘XML’ in the popup menu & choose “XML Source”.
  3. Sidebar on right hand side will appear with source details.
  4. Edit Map field details in this sidebar.
  5. Click on ‘XML Maps’ to view list of maps linked.
  6. Rename, Add, Delete, Assign map schema details in this window.

The same option is also available in Developer Tab “Document Panel” from the Excel Menu. Use this option to assign a new schema or map to the imported XML file.

Note: Similar to editing importing XML, you can create a XML file from Excel directly, by saving it in XML format, right from the ‘File’ menu ‘Save As’ Option.

Import Sitemap to Excel

Bloggers, Web Admin, SEO & Marketing people scan through sitemaps from lot of websites to improve the performance of their pages in search engine result pages. They can use the techniques in this page to import Sitemap from a Website and process all the links within that Domain.

We have completed few quick steps about Extensible Markup Language or XML to Excel converter. This file format is used to exchange data between computer applications across Internet, LAN or apps within same Computer.

This file can be opened in any Internet browsers (Firefox, Chrome, IE, Opera etc.,) or a Text editor directly to view it’s content since it is not a encoded format. But, to view it in a readable format, this article will help more.

By this, you can create your own Excel XML viewer. We have summarized 2 manual methods & 3 different methods using VBA. Be it on-demand process or automation, this complete guide about converting a XML file to Excel will be a handy quick reference.

Источник

Load XML into Excel through VBA

I’ve got a bit of VBA that is loading an XML file through VBA. However when it is imported it is all in one column and not split into a table.

When I manually import this through the Data tab I get the warning there is no schema but asks if I would like Excel to create one based on source data. This then places all the data in a nice table.

I would like this to happen automatically within my current VBA code:

Currently the data then presents itself like this, unstructured. How can I automatically turn this into a table?

2 Answers 2

THE «HARD CODED» WAY IS THIS:

Starting from this

and you want to obtain an excel with two column:

so that we can assume that in your XML you will always have

IMPORTANT: Open up VBA editor in PowerPoint, Excel.. Word and add references to «Microsoft XML, v3.0» (this reference is for Office 2000. you might have others).

Employee.XML

CODE TO READ ABOVE XML

In your case, of course, you need to adapt your routine:

result —> EmpDetails in the code provided
entry —> Employee in the code provided

plus any other necessary adjustment.

In this way you can have as much as many «entry» and «entry child» elements you want.

In fact, looping through all the elements inside your «entry» you will get your COLUMN, then every new entry is a new ROW.

Unfortunately, I don’t have excel on the MAC so I just put the logic, you should check the sintax your own. in this way you build a EXCEL table on the worksheet you want.

THE CORRET WAY SHOULD BE THIS:

You are getting the XML from a URL call, but I strongly suggest to try to work with an XML file on disk at the beginning, and check if it’s correctly valid. So what you should do is get a sample XML from this «WebService» then save it on disk. An try load it in the following way:

Источник

Понравилась статья? Поделить с друзьями:
  • Как открыть xlsx в excel 2016
  • Как открыть xlsx в excel 2003 скачать конвертер
  • Как открыть wordart в word
  • Как открыть word ярлык
  • Как открыть word через командную строку