|
liucqa 发表于 2014-7-18 10:23 
你再仔细测测
下面这段代码,要提取两千多页的网页数据,在循环内使用with createobject("xxx") 造成内存泄漏,经查每页抓取对象实体占3M 内存,当系统内存占用达到1.5G 时excel 崩溃。如前面测试,如果使用Set 语句则程序不会出现问题。- Sub 提取_XMLHTTPP()
-
- Dim URL$, hmlFile, arr(), r, s, i%, j%
-
- Dim t As Single
-
- Dim brr(), crr()
-
- Application.ScreenUpdating = False
-
- Application.DisplayAlerts = False
-
- Application.ShowWindowsInTaskbar = False
-
- On Error Resume Next
-
-
-
- t = Timer
-
- brr = Sheets(1).Range("a1").CurrentRegion.Value
-
-
- For k = 1089 To UBound(brr)
-
- Workbooks.Add
-
-
- URL = "http://www.marketwatch.com/investing/Stock/" & brr(k, 1) & "/financials/income/quarter"
-
-
- With CreateObject("microsoft.xmlhttp")
-
- .Open "GET", URL, False
-
- .send
-
- Do Until .ReadyState = 4
-
- DoEvents
-
- Loop
-
- Set hmlFile = CreateObject("htmlfile")
-
- hmlFile.body.innerhtml = .responsetext
-
- End With
-
-
- Set r = hmlFile.all.tags("table")(0).Rows
-
- ReDim arr(r.Length - 1, r(0).Cells.Length - 1)
-
- For i = 0 To UBound(arr)
-
- For j = 0 To UBound(arr, 2)
-
- arr(i, j) = r(i).Cells(j).innertext
-
- Next
-
- Next
-
-
- Set s = hmlFile.all.tags("table")(1).Rows
-
- ReDim crr(s.Length - 1, s(0).Cells.Length - 1)
-
- For l = 0 To UBound(crr)
-
- For m = 0 To UBound(crr, 2)
-
- crr(l, m) = s(l).Cells(m).innertext
-
- Next
-
- Next
-
- Set hmlFile = Nothing
-
- Set r = Nothing
-
- Set s = Nothing
-
-
- Cells.ClearContents
-
- Range("a1").Resize(UBound(arr) + 1, UBound(arr, 2) + 1) = arr
-
- Range("a" & i + 1).Resize(UBound(crr) + 1, UBound(crr, 2) + 1) = crr
-
- Cells.Columns.AutoFit
-
- ActiveWorkbook.SaveAs "D:" & brr(k, 1) & ".xlsx"
-
- ActiveWorkbook.Close
-
-
-
- Next
-
- Application.ScreenUpdating = True
-
- Application.DisplayAlerts = True
-
- Application.ShowWindowsInTaskbar = True
-
- MsgBox Timer - t
-
-
- End Sub
复制代码 |
|