2011-09-07 197 views
0

我在excel vba中使用QueryTable從網站檢索數據。當工作簿不處於「共享工作簿」模式時,此工作正常。一旦打開「共享工作簿」並運行vba代碼,excel會返回錯誤消息 - 「Microsoft Excel - 此命令在共享工作簿中不可用」。該VBA停止在代碼是Excel VBA QueryTable在「共享工作簿」模式下不受支持

昏暗查詢作爲的QueryTable

集的查詢= Application.ActiveSheet.QueryTables.Add(連接:=網址,目標:=範圍( 「A1」))

。 ..

query.Name = 「獲取數據」 < - 這裏

有檢索數據的另一種方式?

回答

0

您可以刷新共享工作簿中的查詢表。因此,如果它適合您的情況,您可以在模板中設置不共享的查詢,然後共享,然後通過VBA進行刷新。這是最簡單的方法。

如果您不能預先設置它,可以使用MSXML獲取Web數據並使用VBA將其粘貼到工作表中。您需要將參考(VBE - 工具 - 參考)設置爲Microsoft XML,v5.0和Microsoft Forms 2.0對象庫(用於剪貼板)。然後,您可以像這樣運行代碼以從網頁中獲取表格。

Sub GetData() 

    Dim oHttp As MSXML2.XMLHTTP50 
    Dim sHtml As String 
    Dim lTableStart As Long, lTableEnd As Long 
    Dim doClip As MSForms.DataObject 

    Const sTABLESTART As String = "<table id=""table1"">" 
    Const sTABLEEND As String = "</table>" 

    'create a new request object 
    Set oHttp = New MSXML2.XMLHTTP50 

    'open the request and send it 
    oHttp.Open "GET", "http://finance.yahoo.com/q?s=^GSPC", False 
    oHttp.send 

    'get the response - a bunch of html 
    sHtml = oHttp.responseText 

    'define where your data starts and ends 
    lTableStart = InStr(1, sHtml, sTABLESTART) 
    lTableEnd = InStr(lTableStart, sHtml, sTABLEEND) 

    'create a new clipboard object 
    Set doClip = New MSForms.DataObject 

    'set the text and put it in the clipboard 
    doClip.SetText Mid$(sHtml, lTableStart, lTableEnd - lTableStart) 
    doClip.PutInClipboard 

    'one of those rare instances where you actually have to select a range in VBA 
    Sheet4.Range("G10").Select 
    'blank out the previous results 
    Sheet4.Range("G10").CurrentRegion.ClearContents 
    'paste the hmtl as text with no formatting 
    Sheet4.PasteSpecial "Text", , , , , , True 

End Sub 

沒有錯誤在那裏檢查。您可能需要添加一些代碼,以確保您找到該網頁並且它包含您想要的數據。

相關問題