每次进行更改时,我的代码都不会运行

时间:2017-03-09 08:53:21

标签: vba excel-vba excel

我正在使用递减For Loop,因为我要查找的值更接近我上一个活动单元格。但是当我的代码运行时,我发现我的bval和backvalues在某种程度上变得相同。

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim myval As Variant, USERFVAL As Variant, BVAL As Integer, BACKVAL As Integer
    Dim EROW As Integer, COUNTER As Integer

    If Target.Column <> 4 Then Exit Sub 'For preventing undesired code running.`
    If Target.Row < 6 Then Exit Sub
    If IsEmpty(Target(1)) Then Exit Sub
    Application.EnableEvents = False
    ActiveCell.Offset(-1, -2) = ActiveCell.Offset(-2, -2) + 1  'Entered value of (ActiveCell.Offset(-1, 0), "-") = XY-123

    'USERFVAL= uses front value. USERFVAL SHOULD BE XY
    USERFVAL = Split(ActiveCell.Offset(-1, 0), "-")(0)

    'BVAL SHOULD BE 123
    BVAL = Split(ActiveCell.Offset(-1, 0), "-")(1)

    EROW = ActiveSheet.Cells(ActiveSheet.Rows.Count, 4).End(xlUp).Row - 1  'finding the second last used cell

    For COUNTER = EROW To 4 Step -1 'cells(counter,4) should be like xy-245-rd-123
        'myval should be xy
        myval = Split(Cells(COUNTER, 4), "-", 2)(0)
        'BACKVAL shoud be 245
        BACKVAL = Split(Cells(COUNTER, 4), "-")(1) + 1

        If myval = USERFVAL Then 'xy=xy then
             ActiveCell.Offset(-1, 0) = myval & "-" & BACKVAL & "-RD" & -BVAL
            ActiveCell.Offset(-1, 1) = BVAL ` in this cell it does shows correct value of BVAL
            Exit Sub
        End If
    Next COUNTER
End Sub

0 个答案:

没有答案