CountIf返回0值

时间:2017-07-18 08:40:00

标签: excel vba excel-vba

我想在列中找到具有值" orange"在"旧价值"头。 但我得到的值为0虽然我在单元格中有值。请帮助您使用以下代码。

Private Sub CommandButton1_Click()

    Dim x As Workbook

    Dim Wks As Worksheet

    Dim aCell As Range

    Dim col As Long

    Dim Var1

    Dim i As Integer

    Dim a

    Set x = Workbooks.Open("C:\*********\file.xls")

    Set Wks = x.Worksheets("file")

        Set aCell = Wks.Range("A1:X1000").Find(What:="Old Value", LookIn:=xlValues, LookAt:=xlWhole, _
                    MatchCase:=False, SearchFormat:=False)
            col = aCell.Column

       For i = 1 To 1000
            Var1 = Application.WorksheetFunction.CountIf(Wks.Cells(i, col), "*orange*")

            Next i
           MsgBox Var1


End Sub

2 个答案:

答案 0 :(得分:2)

此处不需要

For循环。而不是

For i = 1 To 1000
    Var1 = Application.WorksheetFunction.CountIf(Wks.Cells(i, col), "*orange*")
Next i

Var1 = Application.WorksheetFunction.CountIf(Wks.Columns(col), "*orange*")

答案 1 :(得分:1)

一般来说,这是一个很好的例子,可以做得很少。问题出在循环中,而不是代码的其余部分。

您不会增加var1的值。因此,它每次都被重写。这是增加值的方法:

Public Sub Test()

    Dim Var1 as Long
    Dim i As Long

    For i = 1 To 1000
        Var1 = Var1 + WorksheetFunction.CountIf(ActiveSheet.Cells(i, 4), "*orange*")
    Next i

    Debug.Print Var1

End Sub

结果将在即时窗口中打印出来。