如果发生错误,请忽略并提供空值,然后继续下一个单元格

时间:2019-02-18 12:17:01

标签: vba google-sheets google-api google-sheets-api

我面临的问题是VBA中的错误处理,我的代码运行良好,但是当无法使用Google API分配占位符以进行寻址时,它将占用上一个单元格的地址。我需要说NULL而不是获取上一个单元格的数据并给我重复的数据。

Sub myTest()
On Error Resume Next
If Err.Number <> 0 Then
Value = "Address: NULL "
End If
Dim xhrRequest As XMLHTTP60
Dim domDoc As DOMDocument60
Dim domDoc2 As DOMDocument60
Dim placeID As String
Dim query As String
Dim nodes As IXMLDOMNodeList
Dim node As IXMLDOMNode

Dim rng As Range, cell As Range

Set rng = Range("C2:C3")

For Each cell In rng

'you have to replace spaces with +
query = cell.Value

'You must acquire a google api key and enter it here
Dim googleKey As String
googleKey = "Api Key" 'your api key here

'Send a "GET" request for place/textsearch
Set xhrRequest = New XMLHTTP60

xhrRequest.Open "GET", "https://maps.googleapis.com/maps/api/place/textsearch/xml?" & _
    "query=" & query & "&key=" & googleKey, False
xhrRequest.send

'Save the response into a document
Set domDoc = New DOMDocument60
domDoc.LoadXML xhrRequest.responseText

'Find the first node that is called "place_id" and is the child of the "result" node
placeID = domDoc.SelectSingleNode("//result/place_id").Text

'recycling objects (could just use new ones)
Set domDoc = Nothing
Set xhrRequest = Nothing

'Send a "GET" request for place/details
Set xhrRequest = New XMLHTTP60
xhrRequest.Open "GET", "https://maps.googleapis.com/maps/api/place/details/xml?placeid=" & placeID & _
"&key=" & googleKey, False
xhrRequest.send

'Save the response into a document
Set domDoc = New DOMDocument60
domDoc.LoadXML xhrRequest.responseText

Dim output As String
Dim s As String

'hacky way to get postal code, you might want to rewrite this after learning 
 more
 Set nodes = domDoc.SelectNodes("//result/*")
 For Each node In nodes
 s = node.Text
 If node.nodeName = "formatted_address" Then
    cell.Offset(0, 1).Value = "Address: " & s
End If
Next node

Next cell
'output
'MsgBox "Formatted Address: " & 
domDoc.SelectSingleNode("//result/formatted_address").Text & output
End Sub

这是我得到的: enter image description here

我想要什么: enter image description here

0 个答案:

没有答案