首页 > 解决方案 > 代码在不正确的不同列上运行

问题描述

我有一个在目标列上完美运行的代码。但问题是当有人插入一个新列时,代码无法识别该列由于插入的列而发生了移动。

当代码运行时,它会在错误的列上运行。

有人可以帮助我如何确保代码在所需的列上运行,即使插入了新列。

请看下面的代码:

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim Oldvalue As String
    Dim Newvalue As String

    On Error GoTo Exitsub

    If Target.Column = 24 And Target.Row > 4 And Target.Row < 500 Then
        If Target.SpecialCells(xlCellTypeAllValidation) Is Nothing Then
        GoTo Exitsub
        Else: If Target.Value = "" Then GoTo Exitsub Else
            Application.EnableEvents = False
            Newvalue = Target.Value
            Application.Undo
            Oldvalue = Target.Value
            If Oldvalue = "" Then
                Target.Value = Newvalue
            Else
                Target.Value = Oldvalue & ", " & Newvalue
            End If
        End If
    End If

    Application.EnableEvents = True

Exitsub:
    Application.EnableEvents = True
End Sub

如果插入了新列,这就是运行完美但在错误列上的代码。

标签: excelvba

解决方案


推荐阅读