2017-05-30 81 views
0

我正在运行这个Sub,它正在工作,但是被抓取的数据正在写入第二行,并且每个实例都覆盖了最后一个。我看不到我的脚本错在哪里。请帮助我了解: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 

回答

2
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中的RowCount。但是,一个更好的解决方案是simplilfy你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 
+0

感谢您的建议,不幸的是,在Select Case之外移动RowCount并没有帮助。 然后,我将您的建议替换为选择语句,但它将所有内容都放入D列。 应该如何增加行的增量? – Python

0

我不知道为什么不执行

Case "cardview" 

RowCount = RowCount + 1 

但是,当我下面Case "jobTitle"

移动

 RowCount = RowCount + 1 

它,然后最后的工作。