Excel VBA - 如果语句返回false,则返回#value

时间:2017-05-12 16:30:22

标签: excel vba excel-vba

我正在研究一个更大的Excel宏,但我已经简化了我的代码并发现了我的问题。在下面的if语句中,我可以将rng更改为使该语句为true的单元格,并且它可以正常工作。但是,如果我将其更改为将返回false的单元格(或范围内的单元格),则会返回#value错误。我对VBA很新,所以我做错了什么?

Function count_same(column As Range, row As Range)

Dim rng As Range
Dim cell As Range
Dim result As Long
result = 0

Set rng = Worksheets("Install together 2").Range("f10")

For Each cell In rng.Cells

If WorksheetFunction.IsNumber(WorksheetFunction.Search(row.Value, cell.Value)) Then
    result = result + 1
End If

Next cell

count_same = result

End Function

3 个答案:

答案 0 :(得分:0)

您可以在错误恢复时使用,并进行一些错误检查。您还有列作为范围,但不要在方法中使用它,以便您可以删除它。

Public Function count_same(row As Range)
On Error Resume Next
Dim rng As Range
Dim cell As Range
Dim result As Long
result = 0

Set rng = ThisWorkbook.Sheets("Install together 2").Range("F10")

For Each cell In rng.Cells

    If WorksheetFunction.IsNumber(WorksheetFunction.Search(row.Value, cell.Value)) Then
        If Err.Number <> 0 Then
            Err.Clear
        Else
            result = result + 1
        End If
    End If

Next cell

count_same = result

End Function

答案 1 :(得分:0)

尝试这样的事情:

Function count_same(column As Range, row As Range)

Dim rng As Range
Dim cell As Range
Dim result As Long
result = 0

Set rng = Worksheets("Install together 2").Range("f10")

For Each cell In rng.Cells
    If Not IsError(WorksheetFunction.Search(Row.Value, cell.Value)) Then
        If WorksheetFunction.IsNumber(WorksheetFunction.Search(row.Value, cell.Value)) Then
            result = result + 1
        End If
    End If

Next cell

count_same = result

End Function

从中学习的做法是我们可以预见到潜在的错误。然后我们做的是检查IsError函数的反函数。如果是错误,IsError将返回TRUE。我们只想运行Worksheet函数,如果它不是一个错误。通过If Not IsError,我们实际上是在说“如果这不是错误,那么&#39;。

在您学习VBA时,请尝试防止出现错误,而不是使用On Error Resume NextGoTo,因为这些错误在您开始使用时效果不错,但在您进一步使用时无法使用沿着(每次看到GoTo或On Error语句时,你都会诅咒自己。)

答案 2 :(得分:0)

尝试这样的事情而不是我以前的答案。如果我理解你的需要,这应该可以解决问题。它需要一个输入范围(您想要搜索)和一个带搜索值的输入范围。然后它返回输入范围内该子字符串的实例。

在代码的顶部,我包含了Application.Volatile,它强制它在工作表更改时重新计算。你可以对此发表评论。

Function count_same(InputRange As Range, RowValue As Range, ColValue as Range)
    Application.Volatile

    Dim result As Long
    result = 0

    Dim cell As Range
    For Each cell In InputRange.Cells
        If InStr(1, RowValue.Value, cell.Value, vbTextCompare) > 0 And InStr(1, ColValue.Value, cell.Value, vbTextCompare) > 0 Then
            result = result + 1
        End If
    Next cell

    count_same = result
End Function