VBA Excel - 如果范围内有任何单元格

时间:2016-11-04 15:31:46

标签: excel vba excel-vba

如果某个范围内的任何单元格(本例中为F列)都在数字范围内(46和80),我需要一个MsgBox来一次。下面是我认为可行的代码,但它没有做任何事情。我很确定我的If语句是错的,但我不知道它需要什么。

Sub CheckNumber()
Dim Lastrow As Integer
Dim srchRng As Range

Lastrow = Cells(Rows.Count, 1).End(xlUp).Row
Set srchRng = Range(Cells(84, 6), Cells(Lastrow, 6))

Dim InputValue As String

If WorksheetFunction.CountA(srchRng) > 46 And WorksheetFunction.CountA(srchRng) < 80 Then
frmCMCapsHS.Show
End If
End Sub

3 个答案:

答案 0 :(得分:4)

更改

If WorksheetFunction.CountA(srchRng) > 46 And WorksheetFunction.CountA(srchRng) < 80 Then
frmCMCapsHS.Show
End If

If WorksheetFunction.CountIfs(srchRng, ">46", srchRng, "<80") > 0 Then
frmCMCapsHS.Show
End If

答案 1 :(得分:1)

我认为你需要像这样循环:

dim c as range    
For Each c In srchRng
        If c.Value > 46 And c.Value < 80 Then
            frmCMCapsHS.Show
            Exit For
        End If
    Next

答案 2 :(得分:0)

可能有一种更优雅的方法可以做到这一点,但你可以将它包装在一个函数中并让它循环每个单元格:

Function RangeContains(InputRange As Range, FromVal As Integer, _
    ToVal As Integer) As Boolean

  Dim r As Range
  Dim result As Boolean

  result = False

  For Each r In InputRange
    If r.Value2 >= FromVal And r.Value2 <= ToVal Then
      result = True
      Exit For
    End If
  Next r

  RangeContains = result

End Function

然后按如下方式调用它:

If RangeContains(Range("F:F"), 46, 80) Then
    frmCMCapsHS.Show
End If