我正在从网页上抓取数据。进入最后一页后,如何让宏结束?
例如,如果有4页数据,如何停止并显示4页数据?
共有4页数据。如果在我说的代码
中,我收到1004运行时错误Do While i < 5
...
'Macro to query Delinquency Status Search for DFB Counties
'Run Monday to pull data from Friday
Sub queryActivityDailyMforF()
Dim nextrow As Integer, i As Long
Dim dates
dates = Date - 3
Application.ScreenUpdating = False
Application.DisplayStatusBar = True
Do While i < 4
Application.StatusBar = "Processing Page " & i
nextrow = ActiveSheet.Cells(Rows.Count, "A").End(xlUp).Row + 1
With ActiveSheet.QueryTables.Add(Connection:= _
"URL;https://www.myfloridalicense.com/delinquency_results.asp?SID=&page=" & i & "&county_1=16&county_1=21&county_1=23&county_1=32&county_1=36&county_1=41&county_1=46&county_1=53&county_1=54&county_1=57&county_1=60&county_1=66&status=NS&send_date=" & dates & "&search_1.x=1", _
Destination:=Range("A" & nextrow))
'.Name = _
"2015&search_1.x=40&search_1.y=11&date=on&county_1=AL&lic_num_del=&lic_num_rep=&status=NS&biz_name=&owner_name="
.FieldNames = False
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.BackgroundQuery = True
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.WebSelectionType = xlSpecifiedTables
.WebFormatting = xlWebFormattingNone
.WebTables = "10"
.WebPreFormattedTextToColumns = True
.WebConsecutiveDelimitersAsOne = True
.WebSingleBlockTextImport = False
.WebDisableDateRecognition = False
.WebDisableRedirections = False
.Refresh BackgroundQuery:=False
'autofit columns
Columns("A:G").Select
Selection.EntireColumn.AutoFit
'check for filter, if not then turn on filter
ActiveSheet.AutoFilterMode = False
If Not ActiveSheet.AutoFilterMode Then
ActiveSheet.Range("D2").AutoFilter
End If
i = i + 1
End With
Loop
Application.StatusBar = False
'Align text left
Cells.Select
With Selection
.HorizontalAlignment = xlLeft
.VerticalAlignment = xlBottom
.WrapText = False
.Orientation = 0
.AddIndent = False
.IndentLevel = 0
.ShrinkToFit = False
.ReadingOrder = xlContext
.MergeCells = False
End With
If i = 0 Then Exit Sub
'Loop
End Sub
答案 0 :(得分:0)
我确信有一个更好的答案涉及查询表格或从网站站长获取xml版本的结果,这不是最佳实践但您可以使用错误处理程序。它应该看起来像这样,一般来说:
Sub Stuff()
Do While True
On Error Goto ErrHndl
ErrorProneCode
Loop
LoopExit:
On Error Resume 0
Non_ErrorProneCode
Exit Sub
ErrHndl:
If Err.Number = 1004 Then
Resume LoopExit
Else
Err.Raise Err.Number, Err.Description, Err.Source
End If
End Sub
在上面的示例中,如果ErrorProneCode
sub出现错误,脚本将跳转到ErrHndl:
标签。在那里我们检查1004错误,如果这是我们发现的错误,我们将继续LoopExit:
标签,然后继续。建议您在执行不希望破坏的代码时通过调用On Error Resume 0
来禁用错误处理程序。