2016-06-09 111 views
1

我想使用VBA来凑商品/股票价格从investing.com多页并将它们插入到一个Excel电子表格。VBA刮痧数据从多个网站

下面的代码是我一直努力做一个单一的价格,在这个例子中金:

Sub Extractdatafromwebsite() 

Dim ie As New InternetExplorer 
Dim doc As HTMLDocument 

ie.Visible = False 
ie.navigate "http://uk.investing.com/commodities/gold" 

Do 
    DoEvents 
    Loop Until ie.READYSTATE = READYSTATE_COMPLETE 

Set doc = ie.document 

output = doc.GetElementById("last_last").innerText 
Range("A1").Value = output 

ie.Quit 

End Sub 

不过,我需要从多个站点的数据来获得不同的价格,都在同一时间。

我想详细阐述了代码,我有工作,下面的例子就是我试图显示的黄金和白银的价格,但它只能显示金价在单元格A1 & A2:

Sub Extractdatafromwebsite() 

Dim ie As New InternetExplorer 
Dim doc As HTMLDocument 

ie.Visible = False 
ie.navigate "http://uk.investing.com/commodities/gold" 

Do 
    DoEvents 
    Loop Until ie.READYSTATE = READYSTATE_COMPLETE 

Set doc = ie.document 

output = doc.GetElementById("last_last").innerText 
Range("A1").Value = output 

ie.Quit 

ie.navigate "http://uk.investing.com/commodities/silver" 

Set doc = ie.document 

output = doc.GetElementById("last_last").innerText 
Range("A2").Value = output 

ie.Quit 


End Sub 

请能有人帮助我弄清楚如何得到这个对于多页的工作?我试过搜索,但没有提出任何适合我需要的东西。

而且是有可能得到的东西弹出说像“等待......”而数据进行收集?

感谢

+1

首先,你可能不应该'Quit'的'ie'实例第二个'Navigate'之前,其次,你可能会需要重复'Do..Loop Until'让浏览器的时间来完成加载页... – Dave

+0

谢谢,非常完美,我也有在最初的循环,但它不是工作,取消了退出即和排序它。再次感谢。 –

回答

0

我发现,使用的readyState是不是在这个意义上,该文件还没有完全加载时而可靠的 - 或者至少是对象模型尚未加载。

所以我通常试图访问新的文档对象

这应该为你工作(和@戴夫说,你并不需要使用IE.Quit

Private Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long) 

    Sub Extractdatafromwebsite() 

     Dim ie As New InternetExplorer 
     Dim doc As HTMLDocument   

     ie.Visible = False 
     ie.Navigate "http://uk.investing.com/commodities/gold" 
     Do 
      Sleep 500 
      DoEvents 
     Loop Until ie.ReadyState = 4 ' READYSTATE_COMPLETE 
     Sleep 500 

     Set doc = ie.Document 

     output = doc.GetElementById("last_last").innerText 
     Range("A1").Value = output 

     ie.Navigate "http://uk.investing.com/commodities/silver" 

     Do 
      Sleep 500 
      DoEvents 
     Loop Until ie.ReadyState = 4 ' READYSTATE_COMPLETE 
     Sleep 500 

     Set doc = ie.Document 

     output = doc.GetElementById("last_last").innerText 
     Range("A2").Value = output 

     ie.Quit 
     Set ie = Nothing 

    End Sub 
前添加一个睡眠命令和DOEVENTS
+0

您可以添加'范围(“A1”)。值= output'和'范围(“A2”)。值= output'命令回 – dbmitch

+0

新增的Win32 API睡眠功能的代码的顶部,以防万一你没没那么好用。确保将它放在模块的最顶端,超出所有常量和子例程。让我知道这是否适合你。 – dbmitch