Excel VBA IF大于或小于工作不正常
我试图testing一个单元格的旧值是大于还是小于正在插入的当前值。 然而,它一直说这两者都不是。
我真的不知道为什么…任何人都可以帮我吗?
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
编辑:我已经更新了代码的build议和修复,即使有一个新的问题。 见下面的评论。
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
oldCellValue > curCellValue
和curCellValue < oldCellValue
在技术上是相同的条件。
如果oldcell值= 10,新的cell值= 11
那么oldCellValue > curCellValue
= False (10 >11)
等等
curCellValue < oldCellValue
= False (11 < 10)
将curCellValue < oldCellValue
更改为curCellValue > oldCellValue