让Excel自动写入值

时间:2018-01-29 21:12:26

标签: excel vba excel-vba excel-2010

我有这段代码:

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim KeyCells As Range
    Set KeyCells = Range("A1")

    If Not Intersect(Target, KeyCells) Is Nothing Then
        Range("A2", "A" & KeyCells.Value).ClearContents
        For i = 0 To KeyCells.Value
            Cells(i + 1, "A").Value = i + 1
        Next i
    End If
End Sub

我想在A1中输入一个值,例如10,并且excel列出A2,A3等中的数字1,2,3等。

2 个答案:

答案 0 :(得分:3)

代码中的

Range("A2", "A" & KeyCells.Value)不正确。你可以使用

Range("A2:A" & KeyCells.Value)Range(Range("A2"), Range("A" & KeyCells.Value))

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim i As Long
    Dim KeyCells As Range
    Set KeyCells = Range("A1")

    If Not Intersect(Target, KeyCells) Is Nothing Then
        Range(Range("A2"), Range("A2").End(xlDown)).ClearContents
        For i = 1 To KeyCells.Value
            Cells(i + 1, "A").Value = i
        Next i
    End If
End Sub

答案 1 :(得分:3)

您的范围对象格式错误,在写回工作表之前应始终关闭事件。

Option Explicit

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim i As Long, KeyCells As Range
    Set KeyCells = Range("A1")

    If Not Intersect(Target, KeyCells) Is Nothing Then
        On Error GoTo safe_exit
        Application.EnableEvents = False
        Range("A2:A" & CLng(KeyCells.Value)).ClearContents
        For i = 0 To KeyCells.Value
            Cells(i + 1, "A").Value = i + 1
        Next i
    End If
safe_exit:
        Application.EnableEvents = True
End Sub