我喜欢使用Google Docs函数=importxml(),但很想知道在Excel 2010中是否有类似的功能?我似乎找不到一种方法让程序自动从链接的XML文件中提取数据。
例如,我很想能够设置一列标题为 "项目名称 "的列,然后在下一列中将用户在前一列中输入的项目名称追加到这个网址上。
http://util.eveuniversity.org/xml/itemLookup.php?name=
然后解析产生的XML文件以返回类型ID。这是在google docs中使用
=importxml(concatenate("http://util.eveuniversity.org/xml/itemLookup.php?name=",A3);"//itemLookup/typeID")
A3是具有项目名称的列,在本例中是Tritanium,并以XML文件的形式导入数据。
http://util.eveuniversity.org/xml/itemLookup.php?name=Tritanium
其中返回值34。
我有一个大约20个项目名称的列表,google docs会在每次打开文件时自动更新项目ID。有什么办法让Excel 2010复制这个功能?
谢谢
将
你需要编写自己的UDF。
一种方法是使用 MSXML2
库,这样的东西。
Function GetData(sName As String, sItem As String, Optional sURL = "") As Variant
Dim oHttp As New MSXML2.XMLHTTP60
Dim xmlResp As MSXML2.DOMDocument60
Dim result As Variant
On Error GoTo EH
If sURL = "" Then
sURL = "http://util.eveuniversity.org/xml/itemLookup.php?name="
End If
'open the request and send it'
oHttp.Open "GET", sURL & sName, False
oHttp.Send
'get the response as xml'
Set xmlResp = oHttp.responseXML
' get Item'
GetData = xmlResp.getElementsByTagName(sItem).Item(0).Text
' Examine output of these in the Immediate window'
Debug.Print sName
Debug.Print xmlResp.XML
CleanUp:
On Error Resume Next
Set xmlResp = Nothing
Set oHttp = Nothing
Exit Function
EH:
GetData = CVErr(xlErrValue)
GoTo CleanUp
End Function
这样叫(其中 A5
包含所需的 typeName
)
=GetData(A5, "typeID")
Function ImportXML(url As String, query As String)
Dim document As MSXML2.DOMDocument60
Dim http As New MSXML2.XMLHTTP60
http.Open "GET", url, False
http.send
Set document = http.responseXML
ImportXML = document.SelectSingleNode(query).nodeTypedValue
End Function
数据菜单上的 "来自网络 "功能可以将在线数据直接拉入电子表格。XML数据导入也可以在数据菜单上列出的 "来自其他来源 "子菜单下进行。
创建的连接通过数据菜单上的 "连接 "对话框进行管理。
在创建 "来自网络 "连接时使用记录宏的示例代码。
Sub Macro1()
' Macro1 Macro
With ActiveSheet.QueryTables.Add(Connection:= _
"URL;http://en.wikipedia.org/wiki/Microsoft_Excel" _
, Destination:=Range("$A$1"))
.Name = _
"?affID=110195&tt=270912_7a_3912_6&babsrc=HP_ss&mntrId=3e2fc48700000000000088532eb428ec"
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.BackgroundQuery = True
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.WebSelectionType = xlEntirePage
.WebFormatting = xlWebFormattingNone
.WebPreFormattedTextToColumns = True
.WebConsecutiveDelimitersAsOne = True
.WebSingleBlockTextImport = False
.WebDisableDateRecognition = False
.WebDisableRedirections = False
.Refresh BackgroundQuery:=False
End With
End Sub