使用数组VBA计算多列中的空白单元格

我已经写了一个代码,它给了我一个列/ s中的空白/空白单元格的确切数量。

图片

这显示了如果我运行列A的代码的结果

Sub countblank() Const column_to_test = 2 'column (B) Dim r As Range Set r = Range(Cells(2, column_to_test), Cells(Rows.Count, column_to_test).End(xlUp)) MsgBox ("There are " & r.SpecialCells(xlCellTypeBlanks).Count & " Rows with blank cells in column B") Const columns_to_test = 3 'column (C) Set r = Range(Cells(3, columns_to_test), Cells(Rows.Count, columns_to_test).End(xlUp)) MsgBox ("There are " & r.SpecialCells(xlCellTypeBlanks).Count & " Rows with blank cells in column c ") 'and so on i can count the blanks for as many columns i want End Sub 

但问题如下:

  1. 如果没有空格,这个macros会抛出一个错误,并且会自行终止。 如果我想运行其余的代码呢?
  2. 使用数组或类似的东西,我想同时search多个列的标题,而不是单独的列号,如代码中所示。
  3. 如果find一个空白/ s,它会popup一个Msgbox,但是我们可以在一个名为“error_sheet”的单独的新表中获得错误列表吗?

尝试这个

 Sub countblank() Dim i As Long For i = 2 To 10 ' for looping through the columns Dim r As Range Set r = Range(Cells(2, i), Cells(Rows.Count, i).End(xlUp)) 'for not getting error and adding error messages in the error_sheet 'MsgBox ("There are " & Application.WorksheetFunction.countblank(r) & " Rows with blank cells in column" & r.Column) Sheets("error_sheet").Range(r.Address).Value = "There are " & Application.WorksheetFunction.countblank(r) & " Rows with blank cells in column" & r.Column Next i End Sub 
 Function getBlanksInListCount(ws As Worksheet, Optional FirstRow = 2, Optional TestColumn = 2) With ws getBlanksInListCount = WorksheetFunction.countblank(.Range(.Cells(FirstRow, TestColumn), .Cells(.Rows.Count, TestColumn).End(xlUp))) End With End Function 

尝试子MAIN来检查前三列:

  Sub countblank(column_to_test As Long) Dim r As Range, rr As Range, col As String col = Split(Cells(1, column_to_test).Address, "$")(1) Set r = Range(Cells(2, column_to_test), Cells(Rows.Count, column_to_test).End(xlUp)) On Error Resume Next Set rr = r.SpecialCells(xlCellTypeBlanks) On Error GoTo 0 If rr Is Nothing Then MsgBox ("There are no Rows with blank cells in column " & col) Else MsgBox ("There are " & r.SpecialCells(xlCellTypeBlanks).Count & " Rows with blank cells in column " & col) End If End Sub Sub MAIN() Dim i As Long For i = 1 To 3 Call countblank(i) Next i End Sub 
  1. Q1可以通过使用error handling语句来回答。 error handling语句可以像想要的那样简单或复杂。 下面的一个可能是我第一次去的方法。
 ' if no blank cells found, code continues On Error Resume Next MsgBox ("There are " & r.SpecialCells(xlCellTypeBlanks).Count & _ " Rows with blank cells in column B")