Excel VBA – 为什么数据覆盖同一行?

我正在运行这个小组,它正在工作,但被刮的数据被写入到第二行,每个实例覆盖最后一个。 我看不到我的剧本是错的。 请帮我理解:

Option Explicit Sub test() Dim ele As Object Dim objIE As Object Dim RowCount As Double Dim sht As Worksheet Dim myjobtype As String Dim myzip As String Dim what Dim zipcode Set sht = Sheets("Sheet1") RowCount = 1 sht.Range("A" & RowCount) = "Title" sht.Range("B" & RowCount) = "Company" sht.Range("C" & RowCount) = "Location" sht.Range("D" & RowCount) = "Description" Set objIE = CreateObject("InternetExplorer.Application") myjobtype = InputBox("Enter type of job eg. sales, administration") myzip = InputBox("Enter zipcode of area where you wish to work") With objIE .Visible = True .navigate "http://www.jobs.com/" Do While .Busy Or _ .readyState <> 4 DoEvents Loop Set what = .document.getElementsByName("q") what.Item(0).Value = myjobtype Set zipcode = .document.getElementsByName("where") zipcode.Item(0).Value = myzip .document.forms(0).submit Do While .Busy Or _ .readyState <> 4 DoEvents Loop For Each ele In .document.all Select Case ele.classname Case "cardview" RowCount = RowCount + 1 Case "jobTitle" sht.Range("A" & RowCount) = ele.innertext Case "company" sht.Range("B" & RowCount) = ele.innertext Case "location" sht.Range("C" & RowCount) = ele.innertext Case "preview" sht.Range("D" & RowCount) = ele.innertext End Select Next ele End With Set objIE = Nothing End Sub 

 RowCount = RowCount + 1 

应该移到Select Case之外,紧接在For Each

 For Each ele In .document.all RowCount = RowCount + 1 '<------------------------------- Here Select Case ele.classname Case "cardview" ... 

这将为每个元素增加一行,但对于不匹配任何大小写的元素,您将有空行。 如果你不想要那些空行,你可以简单的递减在Case Else中的Case Else 。 但更好的解决办法是简化您的Select语句,因为所有情况下都采取相同的行动:

 For Each ele In .document.all Select Case ele.classname Case "cardview", "jobTitle", "company", "location", "preview" RowCount = RowCount + 1 sht.Range("D" & RowCount) = ele.innertext End Select Next ele 

我不知道为什么

 Case "cardview" RowCount = RowCount + 1 

没有执行。

但是当我移动

  RowCount = RowCount + 1 

Case "jobTitle"下面

然后它终于工作。