来自NULL的VBA代码#VALUE!归零

时间:2015-02-19 13:40:50

标签: excel vba excel-vba

我使用以下代码从网站检索一些数据。

Public Function giveMeValue(ByVal link As String) As String
   Set htm = CreateObject("htmlFile")

   With CreateObject("msxml2.xmlhttp")
      .Open "POST", link, False
      .send
      htm.body.innerhtml = .responsetext
   End With

   With htm.getelementbyid("JS_topStoreCount")
      giveMeValue = .innerText
   End With

   htm.Close
   Set htm = Nothing
End Function

有时ID为"JS_topStoreCount"的元素不存在,函数返回#VALUE!。如何修改此功能,以便将错误返回为0并以红色突出显示?

1 个答案:

答案 0 :(得分:2)

我无法找到Do Loop的原因,所以我删除了它,我添加了if语句来检查html元素是否为nothing在将其分配给返回值之前。

Public Function giveMeValue(ByVal link As String) As String
Set htm = CreateObject("htmlFile")

With CreateObject("msxml2.xmlhttp")
   .Open "GET", link, False
   .send
   htm.body.innerhtml = .responsetext
End With

If Not htm.getelementbyId("JS_topStoreCount") Is Nothing Then

    giveMeValue = htm.getelementbyId("JS_topStoreCount").innerText

Else

    giveMeValue = "0"

End If

htm.Close
Set htm = Nothing

End Function