我正在尝试测试单元格的旧值是大于还是小于当前插入的值。但是,它一直说它不是。
我真的不知道为什么......任何人都可以帮助我吗?
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
答案 0 :(得分:2)
oldCellValue > curCellValue
和curCellValue < oldCellValue
在技术上是相同的条件。
如果oldcell值= 10且新单元格值= 11
然后oldCellValue > curCellValue
= False (10 >11)
等等
curCellValue < oldCellValue
=错误(11 < 10)
将curCellValue < oldCellValue
更改为curCellValue > oldCellValue