debugging一个QueryTables.Add脚本

Sub FindData() Dim accountNumber As Range Set accountNumber = Range(Range("A2"), Range("A2").End(xlDown)) Dim dataSet As QueryTable For Each Value In accountNumber Set dataSet = .QueryTables.Add( _ Connection:="URL;http://www.prad.org/CamaDisplay.aspx?OutputMode=Display&SearchType=RealEstate&ParcelID=" & Value, _ Destination:=ThisWorkbook.Worksheets(2).Range("A1")) Next Value With dataSet .RefreshOnFileOpen = False .WebFormatting = xlWebFormattingNone .BackgroundQuery = True .WebSelectionType = xlSpecifiedTables .WebTables = "3" End With With Application dataSet.Refresh BackgroundQuery:=False End With End Sub 

这里的最终目标是从URL提取数据并将其放入Worksheet(2)accountNumber的值位于每个页面的URL的末尾以从中绘制数据。

这是我的第一个VBA脚本,马上就给我一个Sub FindData()的错误

我有accountnumbers表。 一个帐户的URL是在最后=后的给定URL。 我正在尝试迭代每个帐户的一个网页,并从每个提取。

 Set dataSet = ActiveSheet.QueryTables.Add( _ Connection:="URL;http://www.prad.org/CamaDisplay.aspx?OutputMode=Display&SearchType=RealEstate&ParcelID=" & Value, _ Destination:=ThisWorkbook.Worksheets(2).Range("A1")) 

QueryTables需要被正确引用。 您可以使用表格限定符,如:表格(“yourname”),QueryTables或其他。 你也可以删除点…

看看我的代码,看看是否有帮助。 我添加了很多评论来帮助你更好地理解整个事情的方式。

 Option Explicit Sub FindData() Const strURL As String = "URL;http://www.prad.org/CamaDisplay.aspx?OutputMode=Display&SearchType=RealEstate&ParcelID=" Dim shActive As Worksheet Dim shDestination As Worksheet Dim oQuery As QueryTable Dim rAccounts As Range Dim rAccount As Range 'Initialize the variables Set shActive = ActiveSheet ' Note the "." in front of the ranges. That's how you use "With" With shActive Set rAccounts = .Range(.Range("A2"), .Range("A2").End(xlDown)) End With ' Remove any old query otherwise they will pile up and slow down ' your workbook Call RemoveSheetQueries(shActive) ' Loop through the accounts and add the queries For Each rAccount In rAccounts Set oQuery = Nothing Set oQuery = shActive.QueryTables.Add(Connection:=strURL & rAccount.Value, _ Destination:=shActive.Range("A1")) ' Set the properties of the new query and eventually run it. With oQuery .RefreshOnFileOpen = False .WebFormatting = xlWebFormattingNone .BackgroundQuery = True .WebSelectionType = xlSpecifiedTables .WebTables = "3" ' This last line will actually get the data .Refresh BackgroundQuery:=False End With Next rAccount End Sub ' Procedure to remove all old Queries Sub RemoveSheetQueries(ByRef shToProcess As Worksheet) Dim lTotal As Long Dim i As Long lTotal = shToProcess.QueryTables.Count For i = lTotal To 1 Step -1 shToProcess.QueryTables(i).Delete Next i End Sub 

我希望它有助于:)