使用数字增量(CTRL拖动)时出现Excel VBA代码错误

时间:2011-04-15 21:36:08

标签: excel vba excel-vba

我已经为我的excel添加了一个VBA代码,它的作用是自动写入其余的数字(例如:当我写2并点击输入时,它将取上面的数字和填写990112 [见img])

当键入每个数字时,此方法正常,但当我使用自动增量(CTRL + Drag)时,它会抛出错误

这是我的VBA代码

Private Sub Worksheet_Change(ByVal Target As Range)
Dim oldText  As String, aboveText As String, newText As String
    If Target.Column = 3 Then
        oldText = Target.Text
        aboveText = Target.Cells(0, 1).Text

        If aboveText <> "DESIGN" Or Target.Text <> "" Then

            If Len(aboveText) = 6 And Len(oldText) < 6 And Len(oldText) >= 1 Then
                Application.EnableEvents = False
                newText = Left(aboveText, 6 - Len(oldText)) + oldText
                Target.Value = newText
                Application.EnableEvents = True
            End If

        End If

    End If

End Sub

Excel File

1 个答案:

答案 0 :(得分:1)

更改

If Target.Column = 3 Then

If Target.Column = 3 And Target.Cells.Count = 1 Then

您正在尝试获取多单元格区域的Text属性(在该情况下,“Target”是C6:C7)。新行将确保您只更改一个单元格。