如何在列中查找任何大于0的数字

时间:2019-01-13 21:14:54

标签: excel vba

我正在尝试编写代码以帮助我在列中查找任何大于0的数字,并在消息框中按数字显示结果。

Dim n
n = 1

Do Until Cells(n + 1, 1) = ""
    n = n + 1
    If Cells(n, 17).Value > 0 Then
        MsgBox Cells(n, 17).Value
    End If
Loop

它应该至少显示3次消息框(基于我现在正在处理的数据表),但我什么都没有!

1 个答案:

答案 0 :(得分:0)

在列中显示正数

您的代码问题可能是因为您一直在“做”直到 A 列中出现“”,但您正在显示 Q ,例如如果 A2 不大于0,将没有消息框。

对于下一个版本

Sub ShowPositive()

    Const cSheet As Variant = "Sheet1"  ' Worksheet Name/Index
    Const cFirstR As Integer = 1        ' First Row Number
    Const cColumn As Variant = 17       ' Column Letter/Number e.g. "Q" or 17

    Dim lastR As Long   ' Last Row Number
    Dim i As Long       ' Row Counter

    With ThisWorkbook.Worksheets(cSheet)
        ' Calculate Last Row Number.
        lastR = .Cells(.Rows.Count, cColumn).End(xlUp).Row
        ' Loop through all rows.
        For i = cFirstR To LastR
            ' Check if current cell contains a number AND
            ' if it is greater than 0.
            If IsNumeric(.Cells(i, cColumn)) And .Cells(i, cColumn) > 0 _
                    Then MsgBox .Cells(i, cColumn)
        Next
    End With

End Sub

执行循环版本

Sub ShowPositive2()

    Const cSheet As Variant = "Sheet1"  ' Worksheet Name/Index
    Const cFirstR As Integer = 1        ' First Row Number
    Const cColumn As Variant = 17       ' Column Letter/Number e.g. "Q" or 17

    Dim n As Long       ' Row Counter

    With ThisWorkbook.Worksheets(cSheet)

        n = cFirstR ' To skip First Row.
        Do Until .Cells(n + 1, cColumn) = ""
            n = n + 1
            If IsNumeric(.Cells(n, cColumn)) And .Cells(n, cColumn) > 0 _
                Then MsgBox .Cells(n, cColumn)
        Loop

    End With

End Sub