在excel宏中优化剪贴板的复制粘贴

时间:2014-09-14 14:59:49

标签: excel vba excel-vba

我从网页中提取html表格数据并将其粘贴到Excel工作表中。从这张表格我将数据提取到另一张表格中。完整的宏需要40秒才能获得网址,其中以下几行需要大约33-37秒。我们非常欢迎任何帮助。

       Set IE = CreateObject("InternetExplorer.Application")
       IE.Navigate strURL1 'Ths is my url
       set doc = IE.Document
       Set tbl = doc.getElementsByTagName("TABLE")(6)
       'copy the tables html to the clipboard and paste to the sheet
       If Not tbl Is Nothing Then
           clip.Clear
           clip.SetText "<table>" & tbl.innerHTML & "</table>"
           clip.PutInClipboard

           'This is the part which is taking the time
           ws1.Select
           ws1.Range("A1").Select
           ws1.PasteSpecial "Unicode Text"
           'This is the part which is taking the time

           clip.Clear
       End If

1 个答案:

答案 0 :(得分:0)

要检索多少行和列?有时循环可能比剪贴板解析操作更快,但行×列必须受到限制。

Dim r As Long, c As Long
Set IE = CreateObject("InternetExplorer.Application")
IE.Navigate strURL1 'Ths is my url
Set doc = IE.Document
Set tbl = doc.getElementsByTagName("TABLE")(6)
'copy the tables html to the clipboard and paste to the sheet
If Not tbl Is Nothing Then
    For r = 0 To (tbl.getElementsByTagName("tr").Length - 1)
        For c = 0 To (tbl.getElementsByTagName("tr")(r).getElementsByTagName("td").Length - 1)
            ws1.Cells(r + 1, c + 1) = tbl.getElementsByTagName("tr")(r).getElementsByTagName("td")(c).innerText
        Next c
    Next r
End If

我没有做过很多行×行粘贴,但是如果可以的话,它会比表格单元格×表格单元格更快。