在表列

时间:2019-07-11 13:55:38

标签: vba counting listobject

我要执行以下操作: '在活动工作表的表格的第1栏中计算所有非空白单元格。 '将此数量的单元格保存为变量“ TransQty”。 “如果计数为0,则显示消息“此选项卡上没有项目标记为过渡”。 “如果计数大于0,则是/否消息“'TransQty'项目将从该选项卡转换。您要继续吗?” '如果为“否”,请结束。 “如果是,请继续执行其余代码。

我想使用表格列的标题,而不是列位置。这样,添加和删除列将不会影响代码的功能。

Sub Transition_from_Queue()

Dim TransRange As Range
Dim TransQty As Integer

Set TransRange = Worksheets("Project Queue").DateBodyRange("TableQueue[Transition]")

For Each TransRange In Selection
    If Application.WorksheetFunction.CountA(TransRange) Then
        TransQty = TransQty + 1
    End If
Next TransRange

If TransQty = 0 Then
    MsgBox "No projects on this tab are marked for transition."
        Else
        If TransQty > 0 Then
            MsgBox Range("TransQty") & "projects will be transitioned from this tab." & vbNewLine & "Would you like to continue?"
        End If
End If

尝试多种不同的代码后,我发现了几个问题。 1)我没有正确识别表列,也无法弄清楚我在做什么错。我想使用列标题,而不是列位置。 2)无论我在目标列的0个单元格还是100个单元格中都有文本,我一直收到TransQty = 0的消息。

1 个答案:

答案 0 :(得分:0)

您的代码非常接近您的需求。在下面的示例中,有两个要点。第一种是将表列直接分配给Range。第二点是如何检查单元格以查看其是否为空。使用COUNTA可以计算整个范围内为空的单元格的数量,但是不能(我认为)是您循环的原因。

Option Explicit

Sub test()
    Dim thisSheet As Worksheet
    Set thisSheet = ActiveSheet

    '--- this is not really needed, but shows how to get a variable
    '    for the whole table
    Dim thisTable As ListObject
    Set thisTable = thisSheet.ListObjects("TableQueue")

    Dim transitionData As Range
    Set transitionData = thisSheet.Range("TableQueue[Transition]")

    '--- this gets you how many non-blank cells in the range
    Dim transQty As Long
    transQty = WorksheetFunction.CountA(transitionData)

    '--- BONUS CODE!!!!  totals up the non-blank data in the range
    '    (though not asked for by OP)
    Dim data As Range
    Dim transitionQty As Double
    For Each data In transitionData
        If Not IsEmpty(data.Value) Then
            transitionQty = transitionQty + data.Value
        End If
    Next data

End Sub