【发布时间】:2015-04-28 15:04:39
【问题描述】:
在两个“表格数据下载”部分之间,第一个表格的行数不固定。
如何添加VBA脚本,使其在第一个表最后使用的行之后自动添加五行,然后开始第二个表的下载?
Sub GetFinanceData()
For x = 1 To 5
Dim URL As String, elemCollection As Object
Dim t As Integer, r As Integer, c As Integer
Dim LastLine As Long
LastLine = Range("A1048576").End(xlUp).Row
Worksheets("Stocks").Select
Worksheets("Stocks").Activate
'Open IE and Go to the Website
URL = "http://stock.finance.sina.com.cn/hkstock/finance/00001.html"
URL = Cells(x, 1)
Set IE = CreateObject("InternetExplorer.Application")
With IE
.navigate URL
.Visible = True
Do While .Busy = True Or .readyState <> 4
Loop
DoEvents
Worksheets.Add(After:=Worksheets(Worksheets.Count)).Name = _
ThisWorkbook.Worksheets("Stocks").Range("B" & x).Value
'Select the Report Type
Set selectItems = IE.Document.getElementsByTagName("select")
For Each i In selectItems
i.Value = "zero"
i.FireEvent ("onchange")
Application.Wait (Now + TimeValue("0:00:05"))
Next i
Do While .Busy: DoEvents: Loop
ActiveSheet.Range("A1:K500").ClearContents
'Find and Get the First Table Data
Set elemCollection = .Document.getElementsByTagName("TABLE")
For t = 0 To (elemCollection.Length - 4)
For r = 0 To (elemCollection(t).Rows.Length - 1)
For c = 0 To (elemCollection(t).Rows(r).Cells.Length - 1)
ActiveSheet.Cells(r + 1, c + 1) = elemCollection(t).Rows(r).Cells(c).innerText
Next c
Next r
Next t
'Find and Get the Second Table Data
Set elemCollection = .Document.getElementsByTagName("TABLE")
For t = 1 To (elemCollection.Length - 3)
For r = 0 To (elemCollection(t).Rows.Length - 1)
For c = 0 To (elemCollection(t).Rows(r).Cells.Length - 1)
ActiveSheet.Cells(r + 19, c + 1) = elemCollection(t).Rows(r).Cells(c).innerText
Next c
Next r
Next t
'Find and Get the Third Table Data
Set elemCollection = .Document.getElementsByTagName("TABLE")
For t = 2 To (elemCollection.Length - 2)
For r = 0 To (elemCollection(t).Rows.Length - 1)
For c = 0 To (elemCollection(t).Rows(r).Cells.Length - 1)
ActiveSheet.Cells(r + 48, c + 1) = elemCollection(t).Rows(r).Cells(c).innerText
Next c
Next r
Next t
'Find and Get the Fourth Table Data
Set elemCollection = .Document.getElementsByTagName("TABLE")
For t = 3 To (elemCollection.Length - 1)
For r = 0 To (elemCollection(t).Rows.Length - 1)
For c = 0 To (elemCollection(t).Rows(r).Cells.Length - 1)
ActiveSheet.Cells(r + 61, c + 1) = elemCollection(t).Rows(r).Cells(c).innerText
Next c
Next r
Next t
End With
' cleaning up memory
IE.Quit
Next x
End Sub
【问题讨论】:
-
好的,我正在想象您从一张空白纸开始(在 ClearContents 之后),然后导入第一个表来表示第 1 到 90 行,然后导入表 2 来表示第 96 到 145 行。如果我是对,您真的要插入 5 行还是只是将行计数器增加 5?如果我了解您的情况,这似乎是无意义的操作。
-
嗨,马克,第一个表 --> 插入 5 行 --> 下一个表--> 插入 5 行--> 下一个表,遵循此模式。提前致谢!
-
另一件事我似乎无法弄清楚。
For t = 0 To (elemCollection.Length - 4)如果这组三个循环只是为了导出第一个表,为什么存在外循环?为什么不用t = 0替换外循环? -
嗨,Mark 抱歉误导,实际上有四个表,我刚刚发布了两个简化的原因,现在我更新了四个完整的表,你能再帮忙吗?