在A列中查找空白单元格并对其进行计数

时间:2014-07-02 03:28:55

标签: excel vba excel-vba

我想帮助创建一个宏来检查表2的A列并计算空白单元格的数量。如果该数字等于0,我希望它继续让它转到宏的另一部分(让我们称之为alpha)。如果数字大于0,你希望它转到一个单独的部分(我们称之为测试版)。

我知道= COUNTBLANK是一个公式,但为此创建一个宏会有所帮助。

到目前为止,我有:

Dim rng as Range
Set rng = Sheets ("Xml").Range("A1:A7000")
NumberOfBlankRows = WorkSheetFunction.CountBlank(rng)

If NumberOfBlankRows = 0 Then
    GoTo ----This is the part where I want it to go to Alpha----
Else
    GoTo ----This is the part where I want it to go to Beta----
EndIf

1 个答案:

答案 0 :(得分:0)

如果我理解正确,您将寻求如何在子过程中实现goto机制。解决方案就像在sub的主体之后添加标记的Alpha和Beta代码块并处理退出点一样简单,如下所示:

 Sub delegate()

            Dim rng as Range
            Set rng = Sheets ("Xml").Range("A1:A7000")
            NumberOfBlankRows = WorkSheetFunction.CountBlank(rng)

            If NumberOfBlankRows = 0 Then
                GoTo Alpha
            Else
                GoTo Beta
            EndIf

            Exit Sub

        Alpha:
            ' Alpha's body goes here
            Exit Sub

        Beta:
            ' Beta's body goes here
            Exit Sub

 End Sub

一般来说,goto语句被认为是 evil ,因为它们掩盖了导致狡猾错误的代码流。另外,这种技术不必要地使子体膨胀。考虑将Alpha和Beta移动到他们自己的子(或者如果需要的话,可以使用函数)。

我提供了一个更通用的示例,我的解决方案适用于任何列,工作表和工作簿。我的解决方案检查所选列与其与所选工作表的usedRange的交集。如果我们检查列的所有单元格的空白,它将总是有一些空白 - 除非你有这么大的数据集使用所有1,048,576行!

Sub delegate(A1col As String, Optional shName As String = "", Optional wb As workbook)

    Dim sh As Worksheet, usedColumnCells As Range
    If wb Is Nothing Then Set wb = activeworkbook

    If shName = "" Then
        Set sh = wb.ActiveSheet
    Else
        On Error GoTo no_such_sheet
        Set sh = wb.Worksheets(shName)
    End If

    Set usedColumnCells = Application.Intersect(sh.usedRange, sh.Range(A1col & ":" & A1col))

    If usedColumnCells Is Nothing Then
        ' Call B as all cells in chosen column are blank
        beta
        Exit Sub
    End If

    ' get total blanks in usedColumnCells
    Dim totalColBlanks As Long
    totalColBlanks = Application.WorksheetFunction.CountBlank(usedColumnCells)

    ' proceed with the delegation of tasks based on number of totalColBlanks
    If totalColBlanks = 0 Then
        ' call A procedure
        alpha
    ElseIf totalColBlanks > 0 Then
        ' call B procedure
        beta
    End If

    Exit Sub

' error handler
no_such_sheet:
    If Err.Number = 9 Then
        MsgBox ("There is no worksheet named: " & shName)
    End If

End Sub

Sub alpha()
    MsgBox ("I am alpha")
End Sub

Sub beta()
    MsgBox ("I am beta")
End Sub

以下是如何调用上述过程来检查示例的第A列" xml "工作表:

call delegate ("a", "xml")