Excel VBA IF大于或小于不能正常工作



我正在尝试测试一个单元格的旧值是否大于或小于正在插入的当前值。然而,它一直说两者都不是。

我真的不知道为什么。。。有人能帮我吗?

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

oldCellValue > curCellValuecurCellValue < oldCellValue在技术上是相同的条件。

如果旧单元格值=10且新单元格值=11

则CCD_ 3=假CCD_ 4

也是

curCellValue < oldCellValue=错误(11 < 10)

curCellValue < oldCellValue更改为curCellValue > oldCellValue

最新更新