VBA 通过单元格中的公式计算值时类型不匹配

VBA type mismatch when value is calculated by a formula in the cell

Private Sub Worksheet_Change(ByVal Target As Range)
Dim KeyCells As Range

Set KeyCells = Range("F2:F220")
 
If Not Application.Intersect(KeyCells, Range(Target.Address)) _
       Is Nothing Then

If Range("G2:G220").Value < 0 Then
    MsgBox "Cell " & Target.Address & " has changed."

End If 
End If
End Sub

G 列中有一个公式可根据 F 列中的数字计算值。当 G 中的结果为负值时,我想要一个弹出窗口。类型不匹配位于行 If Range("G2:G220") ... 列的格式为数字,但显示为 Variant/Variant。我想这是因为单元格内容实际上是一个公式?

有没有办法在不引入 'helper' 列的情况下解决这个问题?

这只是我的第二部分 VBA 所以如果您发现任何其他错误,我很高兴听到!

像这样的东西应该可以工作:

Private Sub Worksheet_Change(ByVal Target As Range)

    Dim rng As Range, c As Range
    
    Set rng = Application.Intersect(Range("F2:F220"), Target) 'Target is already a Range...
    'any changed cells in F2:F220 ? 
    If Not rng Is Nothing Then
        'loop over the changed cell(s)
        For Each c in rng.Cells
            'check value in ColG...   
            If c.Offset(0, 1).Value < 0 Then
                MsgBox "Cell " & c.Address & " has changed."
            End If
        Next c 
    End If

End Sub

编辑:我知道你是否想知道 Col G 中是否有 any 个负数,或者你是否想跟踪 row-by-row 并不完全清楚。此代码执行后者。

限制结果数量

Option Explicit

Private Sub Worksheet_Change(ByVal Target As Range)
    
    Const KeyAddress As String = "F2:F220"
    Const CheckColumn As Variant = "G" ' e.g. "A" or 1
    Const MaxResults As Long = 1
    
    ' Define 'KeyCells'.
    Dim KeyCells As Range: Set KeyCells = Range(KeyAddress)
    ' Define the range of cells that have changed and are part of 'KeyCells'.
    Dim rng As Range: Set rng = Application.Intersect(Target, KeyCells)
    ' Check if there are any cells that have changed and are part of 'KeyCells'.
    If rng Is Nothing Then Exit Sub
    ' Check if there is more than 'MaxResults' cells that have changed and
    ' are part of 'KeyCells'.
    If rng.Cells.Count > MaxResults Then GoSub checkMoreCells
    
    ' Calculate the offset between 'Key' and 'Check' columns.
    Dim ColOff As Long: ColOff = Columns(CheckColumn).Column - KeyCells.Column
    
    Dim cel As Range
    For Each cel In rng.Cells
        ' Check if the value in 'Check' column is negative.
        If cel.Offset(, ColOff).Value < 0 Then
            MsgBox "Cell '" & cel.Address(False, False) & "' has changed " _
                 & "to '" & cel.Value & "'."
        End If
    Next cel

    Exit Sub

checkMoreCells:
    Dim msg As Variant
    msg = MsgBox("There could be '" & rng.Cells.Count & "' results. " _
               & "Are you sure you want to continue?", _
               vbYesNo + vbCritical, _
               "More Than One Cell")
    If msg = vbYes Then Return
    Exit Sub

End Sub