excel - VBA将文本从IE复制到Excel

标签 excel internet-explorer vbscript copy

任何人都可以帮助我使用一个简单的 Visual Basic 脚本将字段 qwidget_lastsale 从以下网站复制到 Excel 工作表吗?

http://www.nasdaq.com/symbol/abt/recommendations

我一直在尝试修改现有脚本,但似乎无法使其工作。到目前为止,我可以打开网站和 Excel,但无法复制该字段。

我想要在此之后的复制脚本:

Set objExplorer = CreateObject("InternetExplorer.Application")
WebSite = "http://www.nasdaq.com/symbol/abt/recommendations"
with objExplorer
.Navigate2 WebSite
.left=5
.top=5
.height=1100
.width=700
.AddressBar = 0
.Visible = 1
.ToolBar = 0
.StatusBar = 1
WScript.Sleep 1000
Set objIE = Nothing
end with

Set xl = CreateObject("Excel.application")
xl.Application.Workbooks.Open "C:\Users\user\Documents\testauto.xlsx"
xl.Application.Visible = True

最佳答案

您需要使用 DOM 操作,并且不要这么快从内存中释放 objExplorer:

Set objExplorer = CreateObject("InternetExplorer.Application")

WebSite = "http://www.nasdaq.com/symbol/abt/recommendations"
Const READYSTATE_COMPLETE As Long = 4

With objExplorer
    .Navigate2 WebSite
    .Left=5
    .Top=5
    .Height=1100
    .Width=700
    .AddressBar = 0
    .Visible = 1
    .ToolBar = 0
    .StatusBar = 1
    '//WScript.Sleep 1000
    Do Until .ReadyState = READYSTATE_COMPLETE
        WScript.Sleep 1000
    Loop
    '//Set objIE = Nothing (your variable isn't called 'objIE' anyway?)
End With

Set xl = CreateObject("Excel.Application")
    xl.Visible = True

Set wb = xl.Workbooks.Open("C:\Users\user\Documents\testauto.xlsx")
Set ws = wb.Sheets("Sheet1") '// Change name of sheet as required

ws.Range("A1").Value = objExplorer.Document.getElementById("qwidget_lastsale").Value

'// Rest of code....
'// ...

'// NOW clear down your variables.
objExplorer.Quit

wb.Close SaveChanges:=True
xl.Quit

Set ws = Nothing
Set wb = Nothing
Set xl = Nothing
Set objExplorer = Nothing

此外,正如您在上面看到的,我更改了一些内容:

  • Internet Explorer 有 READYSTATE enumeration返回一个Long。您可以测试一下页面是否已加载,而不是休眠 1 秒并希望得到最好的结果...

  • 当您使用 CreateObject("Excel.Application") 创建 Excel 实例时,返回的对象是应用程序对象 - 无需再次引用它。你会注意到我把它们拿出来了。

  • 与 Excel 工作簿交互时,最好分别使用 ApplicationWorkbookWorksheet 对象的变量,并使用此变量。这可以确保您始终处于您想要的工作表上,并在正确的时间关闭正确的工作簿。 p>

  • 代码缩进是你的 friend - 它使所有内容都更容易阅读和遵循。

关于excel - VBA将文本从IE复制到Excel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37523933/

相关文章:

javascript - 给 HTML 时间来呈现其文本

excel - 在给定 Range 对象的 VBA 中循环遍历两个相同长度的单元格范围

excel - 如何更换一个?通过 é 在 Excel 工作表中

vba - 将模板行复制并粘贴到事件单元格下方的行

在 IE10 中重新加载另一个框架时,Java Applet 失败/消失

string - 如何打乱字符串中的字符?

excel - 有没有办法通过 openpyxl 保留或添加下拉菜单到 Excel?

javascript - 防止 IE 包裹在 contenteditables 中的 P 元素中

c# - IE 子域登录在登录父域时不起作用

javascript - VBScript 慢字节数组复制