如何解决通过单元格中的公式计算值时,VBA类型不匹配
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") ...
上,该列的格式为Number,但显示为Variant / Variant。我认为这是因为单元格内容实际上是一个公式?
在不引入“帮助”列的情况下是否可以解决此问题?
这只是我的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中是否存在任何负数,或者是否要逐行跟踪,尚不清楚。这段代码是后者。
,限制结果数量
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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。