2017-05-13 26 views
0

如果我运行我的代码保持行“在错误恢复下一个”在它,它工作正常,但如果我拿出这条线,然后它停止显示错误“对象变量或者块变量未设置“。为什么发生这种情况,如果我喜欢在没有“错误恢复下一步”的情况下运行我的脚本,那我该怎么做?预先感谢您看看它。抖动错误,而不使用“错误恢复下一步”

Sub CandyCrush() 
Dim http As New MSXML2.XMLHTTP60, html As New HTMLDocument 
Dim Items As Object, Item As Object 

With http 
    .Open "GET", "https://itunes.apple.com/us/app/candy-crush-saga/id553834731?mt=8", False 
    .send 
    html.body.innerHTML = .responseText 
End With 

Set Items = html.getElementsByClassName("left") 
    On Error Resume Next 
    For Each Item In Items 
     x = x + 1 
     Cells(x, 1) = Item.getElementsByTagName("h1")(0).innerText 
     Cells(x, 2) = Item.getElementsByTagName("h2")(0).innerText 
    Next Item 
End Sub 

要素类N TAG:

<div class="left"> 
       <h1 itemprop="name">Candy Crush Saga</h1> 
       <h2>By King</h2> 
       <div class="editorial-badge">Essentials</div> 
      </div> 

延长部:

Sub RealYP() 
Const URL = "https://www.yellowpages.com/search?search_terms=Coffee%20Shops&geo_location_terms=San%20Francisco%2C%20CA&page=2" 
Dim html As New HTMLDocument, topics As Object, topic As HTMLHtmlElement 

With CreateObject("MSXML2.serverXMLHTTP") 
    .Open "GET", URL, False 
    .send 
    html.body.innerHTML = .responseText 
End With 
Set topics = html.getElementsByClassName("info") 
    On Error Resume Next 
    For Each topic In topics 
     x = x + 1 
     If CBool(topic.getElementsByClassName("track-visit-website").lentgh) Then _ 
     Cells(x, 1) = topic.getElementsByClassName("track-visit-website")(0).href 
    Next topic 
End Sub 

回答

1

我通常检查,看看是否元素试图访问它始终定义父之前就存在单元格工作表。

with worksheets("sheet1") 
    For Each Item In Items 
     x = x + 1 
     if cbool(Item.getElementsByTagName("h1").length) then _ 
      .Cells(x, 1) = Item.getElementsByTagName("h1")(0).innerText 
     if cbool(Item.getElementsByTagName("h2").length) then _ 
      .Cells(x, 2) = Item.getElementsByTagName("h2")(0).innerText 
    Next Item 
end with 

如果你运行这个,发现有一个在列A和B空单元格的行,然后有一个div元素(类=“左”)不包含在H1和H2元素。

A。零的长度表示没有(基于一个索引)。但是,访问元素是从零开始的索引,因此第一个元素(如果存在)是.getElementsByTagName("h2")(0)

+0

OMG !!!!!!!!!!这对我来说完全是陌生的 - CBool​​的东西。完美的作品。谢谢先生,Jeeped提供了一个很好的解决方案。 – SIM

+0

顺便说一句,如果我不够不礼貌地要求包含具有相同逻辑的另一个代码的扩展部分不起作用,那么您可以在业余时间中查看一下。谢谢。 – SIM