我正在研究一个VBA脚本,而且我仍然坚持应该如此简单的事情。无论如何,VBA代码从sheet1获取一个成员编号,打开一个经过身份验证的IE窗口,弹出一个成员编号,从HTML页面中抓取某些表并将它们插入到Sheet 2中。然后它转到Sheet1中的下一个成员编号。但是我正在努力将已删除的数据转换为sheet2。当我运行代码时,一切都按计划进行,除了每次都将所有内容都插入到sheet2中的相同位置。因此,当代码完成时,我所拥有的是来自sheet1上最后一个成员的数据。
Option Explicit
Sub TableExample()
Dim IE As Object
Dim doc As Object
Dim strURL As String
Dim hicN As String
strURL = "exampleURL.com"
Set IE = CreateObject("InternetExplorer.Application")
With IE
.Visible = True
.navigate strURL
Do Until .ReadyState = 4: DoEvents: Loop
Do While .Busy: DoEvents: Loop
Set doc = IE.Document
Do Until IsEmpty(ActiveCell)
memNum = ActiveCell
doc.getelementbyid("claimNumber").Value = memNum
doc.all("submitBtn").Click
Do While .Busy: DoEvents: Loop
GetAllTables doc, memNum
ActiveCell.Offset(1, 0).Select
Loop
'.Quit
End With
End Sub
GetAllTables方法 -
Sub GetAllTables(doc As Object, memNum As String)
' get all the tables from a webpage document, doc, and put them in a new worksheet
Dim ws As Worksheet
Dim rng As Range
Dim tbl As Object
Dim rw As Object
Dim cl As Object
Dim tabno As Long
Dim nextrow As Long
Dim I As Long
Set ws = Sheet2
For Each tbl In doc.getElementsByTagName("TABLE")
tabno = tabno + 1
If tabno = 11 Or tabno = 13 Or tabno = 16 Then
nextrow = nextrow + 1
Set rng = ws.Range("B" & nextrow)
'Debug.Print nextrow
rng.Offset(, -1) = memNum
For Each rw In tbl.Rows
For Each cl In rw.Cells
rng.Value = cl.outerText
Set rng = rng.Offset(, 1)
I = I + 1
Next cl
nextrow = nextrow + 1
Set rng = rng.Offset(1, -I)
I = 0
Next rw
End If
Next tbl
End Sub
答案 0 :(得分:1)
将nextrow
声明为全局变量,它应该可以正常工作
答案 1 :(得分:1)
而不是
Set rng = ws.Range("B" & nextrow)
使用此
它会将数据放在下一个可用行 - 列B
中 With ws
Set rng = .Range("B" & .Range("B" & Rows.Count).End(xlUp).Row).Offset(1, 0)
End With