作为 VBA 新手,任何帮助将不胜感激。我的程序的基本点是循环遍历电子表格的列,并计算指定范围内每列中非空白单元格的数量。 这是我的电子表格的示例。
当列中的所有单元格均为空白时,VBA 会抛出 1004 错误,未找到单元格。我想做的是,如果发生1004错误,则将非空白单元格(nonBlank = 0)的计数设置为零,如果没有发生错误,则正常计数。在Python之类的东西中,我会使用try/except。这是我的尝试。
For i = 1 To 3
On Error Resume Next
Set selec_cells = Sheet1.Range(Sheet1.Cells(FirstRow, i), Sheet1.Cells(LastRow, i)).SpecialCells(xlCellTypeVisible).Cells.SpecialCells(xlCellTypeConstants)
If Err.Number <> 1004 Then
nonBlank = 0
Else
nonBlank = selec_cells.Count
End If
On Error GoTo -1
Next i
我的问题是,当我运行此代码时,它每次都会输出 0,即使第 2 列应该返回 3。谢谢!
编辑: selec_cells 是抛出错误的原因。
最佳答案
错误处理
VBA
中没有On Error Goto -1
,这是一个VB
东西(那些是不同页面的链接)。一个提示是,如果您在 google 上搜索VBA
内容,只需将VBA
放在您要查找的内容前面即可。使用
On Error Resume Next
(延迟错误捕获)时,您应该最多将其“应用”在一两行上,并使用On Error Goto 0
(禁用错误捕获)或使用另一个错误处理程序。您对
On Error Resume Next
的使用是 Not Acceptable ,因为在这种特殊情况下,我们可以测试范围:1. 推迟错误处理,2. 尝试设置范围,3. 禁用错误处理。如果出现错误,则不会设置范围,因此If Not rg Is Nothing Then
可以翻译为类似 'If rg Is Something then' (双重否定)或如果已创建对范围的引用,则。第二个解决方案说明了一种情况,其中主错误处理程序正在处理除
SpecialCells
错误之外的所有错误,该错误有自己的错误处理程序。Resume Next
表示继续发生错误的行之后的行。请注意Exit Sub
行并注意Resume ProcExit
,其中代码被重定向到标签。下面说明了处理此问题的两种方法。在此阶段,我建议您使用第一个,并记住在使用
On Error Resume Next
时使用“结束”On Error Goto 0
(一两行) )。
代码
Option Explicit
Sub testOnErrorResumeNext()
Const FirstRow As Long = 2
Const LastRow As Long = 11
Dim rg As Range ' ... additionally means 'Set rg = Nothing'.
Dim nonBlank As Long ' ... additionally means 'nonBlank = 0'.
Dim j As Long
For j = 1 To 3 ' Since it's a column counter, 'j' or 'c' seems preferred.
' Since you're in a loop, you need the following line.
Set rg = Nothing
On Error Resume Next
Set rg = Sheet1.Range(Sheet1.Cells(FirstRow, j), _
Sheet1.Cells(LastRow, j)).SpecialCells(xlCellTypeVisible) _
.Cells.SpecialCells(xlCellTypeConstants)
On Error GoTo 0
If Not rg Is Nothing Then
nonBlank = rg.Cells.Count
Else
' Since you're in a loop, you need the following line.
nonBlank = 0
End If
Debug.Print nonBlank
Next j
End Sub
Sub testOnError()
On Error GoTo clearError
Const FirstRow As Long = 2
Const LastRow As Long = 11
Dim rg As Range ' ... additionally means 'Set rg = Nothing'.
Dim nonBlank As Long ' ... additionally means 'nonBlank = 0'.
Dim j As Long
For j = 1 To 3 ' Since it's a column counter, 'j' or 'c' seems preferred.
' Since you're in a loop, you need the following line.
Set rg = Nothing
On Error GoTo SpecialCellsHandler
Set rg = Sheet1.Range(Sheet1.Cells(FirstRow, j), _
Sheet1.Cells(LastRow, j)).SpecialCells(xlCellTypeVisible) _
.Cells.SpecialCells(xlCellTypeConstants)
On Error GoTo clearError
If Not rg Is Nothing Then
nonBlank = rg.Cells.Count
End If
Debug.Print nonBlank
Next j
ProcExit:
Exit Sub ' Note this.
SpecialCellsHandler:
' Since you're in a loop, you need the following line.
nonBlank = 0
Resume Next
clearError:
MsgBox "Run-time error '" & Err.Number & "': " & Err.Description
Resume ProcExit
End Sub
关于excel - 使用 Resume Next 循环中的错误处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66069280/