我想测试一个单元格的旧值是大于还是小于当前插入值。但是,它一直说它既不是。Excel的VBA如果大于或小于不能正常工作
我真的不知道为什么......任何人都可以帮我解决问题吗?
Dim oldCellValue As Integer
Dim curSheetName As String
Dim curCellAddress As String
Dim curCellValue As Integer
Public Sub Worksheet_SelectionChange(ByVal Target As Range)
oldCellValue = Target.Value
End Sub
Private Sub Worksheet_Change(ByVal Target As Range)
curSheetName = ActiveSheet.Name
curCellAddress = ActiveCell.Offset(-1, 0).Address
curCellValue = ActiveCell.Offset(-1, 0).Value
If oldCellValue = 0 And curCellValue = 0 Then
Exit Sub
Else
With Application
.ScreenUpdating = False
.DisplayAlerts = False
.EnableEvents = False
End With
Set Workbook = Workbooks.Open("stock.xlsx")
If oldCellValue > curCellValue Then
Sheets(curSheetName).Range(curCellAddress) = ActiveCell.Value + (oldCellValue - curCellValue)
ElseIf curCellValue < oldCellValue Then
Sheets(curSheetName).Range(curCellAddress) = ActiveCell.Value - (curCellValue - oldCellValue)
Else
MsgBox "Neither"
End If
Workbook.Save
Workbook.Close
With Application
.ScreenUpdating = True
.DisplayAlerts = True
.EnableEvents = True
End With
End If
End Sub
编辑:我已经更新了建议和修复代码,即使有一个新的问题。见下面的评论。
Dim oldCellValue As Integer
Dim curSheetName As String
Dim curCellAddress As String
Dim curCellValue As Integer
Public Sub Worksheet_SelectionChange(ByVal Target As Range)
oldCellValue = Target.Value
End Sub
Private Sub Worksheet_Change(ByVal Target As Range)
curSheetName = ActiveSheet.Name
curCellAddress = Target.Address
curCellValue = Target.Value
If oldCellValue = 0 And curCellValue = 0 Or oldCellValue = curCellValue Then
Exit Sub
Else
With Application
.ScreenUpdating = False
.DisplayAlerts = False
.EnableEvents = False
End With
Set Workbook = Workbooks.Open("stock.xlsx")
If oldCellValue > curCellValue Then
Sheets(curSheetName).Range(curCellAddress) = ActiveCell.Value + (oldCellValue - curCellValue)
MsgBox ActiveCell.Value
Else
Sheets(curSheetName).Range(curCellAddress) = ActiveCell.Value - (curCellValue - oldCellValue)
MsgBox ActiveCell.Value
End If
Workbook.Save
Workbook.Close
With Application
.ScreenUpdating = True
.DisplayAlerts = True
.EnableEvents = True
End With
End If
End Sub
你的数据是什么样的?两个细胞的上下彼此确实相等吗?在'Change'中,尝试使用'Target'而不是'ActiveCell',看看是否有帮助。 – cxw
在您的'Change'事件处理程序中,您设置了'curCellValue = ActiveCell.Offset(-1,0).Value',这看起来可能是错误的逻辑。为什么不是'curCellValue = Target.Value'? –
在评估If/ElseIf时,'oldCellValue'和'curCellValue'的值是什么?如果您不知道,请使用Print/MsgBox的调试技术或断点检查Locals窗口中的数据。 –