Do Until循环需要重新启动时出错

我在VBA中有一个Do Until循环。

我的问题是,运行macros时大部分时间都可能会出现错误,因为并非所有工作表都有信息。

当发生这种情况时,我只想再次启动循环。 我假设它不是“On Error Resume Next”我正在考虑自动filter上的行数,然后如果它是1(即只有标题)再次启动循环。 只是不知道该怎么做。

Dim rngDates As Range'range where date is paste on。 'Dim strDate As String Dim intNoOfRows As Integer Dim rng As Range

Sub Dates() Application.ScreenUpdating = False Set rngWorksheetNames = Worksheets("info sheet").Range("a1") dbleDate = Worksheets("front sheet").Range("f13") Worksheets("info sheet").Activate Range("a1").Activate Do Until ActiveCell = "" strSheet = ActiveCell Set wsFiltering = Worksheets(strSheet) intLastRow = wsFiltering.Cells(Rows.Count, "b").End(xlUp).Row Set rngFilter = wsFiltering.Range("a1:a" & intLastRow) With rngFilter .AutoFilter Field:=1, Criteria1:="=" On Error Resume Next Set rngDates = .Resize(.Rows.Count - 1, 1).Offset(1, 0).SpecialCells(xlCellTypeVisible) End With With rngDates .Value = dbleDate .NumberFormat = "dd/mm/yyyy" If wsFiltering.FilterMode Then wsFiltering.ShowAllData End If ActiveCell.Offset(1, 0).Select End With Application.ScreenUpdating = True Worksheets("front sheet").Select MsgBox ("Dates updated") Loop 

通过使用SUBTOTAL公式筛选后可以检查数据的存在。

 If Application.WorkSheetFunction.Subtotal(103,ActiveSheet.Columns(1)) > 1 Then 'There is data Else 'There is no data (just header row) End If 

你可以在这里阅读关于SUBTOTAL


不要使用Do Until循环,而应考虑在Worksheets集合上使用For Each循环。

即。

 Sub ForEachWorksheetExample() Dim sht As Worksheet 'go to error handler if there is an error On Error GoTo err 'loop through all the worksheets in this workbook For Each sht In ThisWorkbook.Worksheets 'excute code if the sheet is not the summary page 'and if there is some data in the worksheet (CountA) '(this may have to be adjusted if you have header rows) If sht.Name <> "front sheet" And _ Application.WorksheetFunction.CountA(sht.Cells) > 0 Then 'do some stuff in here. Refer to sht as the current worksheet End If Next sht Exit Sub err: MsgBox err.Description End Sub 

也。 我build议删除On Error Resume Next语句。 处理错误和处理错误要好得多,而不是忽略它们。 这可能会导致奇怪的结果。