在VBA中设置变量范围

时间:2018-11-21 15:35:01

标签: excel vba excel-vba

我有一个我要创建的函数,该函数基本上会清除如果前一个单元格中的下拉列表发生更改时选择的下拉列表。我需要重复很多行。当前它说我的变量未定义

Private Sub Worksheet_Change(ByVal Target As Range)

For i = 17 To 1015
If Target.Cells.Count > 1 Then Exit Sub

If Not Intersect(Target, Range("D" & i)) Is Nothing Then
    Range("E" & i).ClearContents
End If


End Sub

2 个答案:

答案 0 :(得分:3)

此错误意味着您需要声明变量i并指定类型,然后才能使用它。您可以通过Dim i As Long执行此操作。

另外,您将需要Next i来告知循环在哪里结束。

If Target.Cells.Count > 1 Then Exit Sub仅测试一次(循环外)。

Option Explicit

Private Sub Worksheet_Change(ByVal Target As Range)
    If Target.Cells.Count > 1 Then Exit Sub

    Dim i As Long
    For i = 17 To 1015
        If Not Intersect(Target, Range("D" & i)) Is Nothing Then
            Range("E" & i).ClearContents
        End If
    Next i
End Sub

没有测试,但这应该给出相同的结果:

Option Explicit

Private Sub Worksheet_Change(ByVal Target As Range)
    If Target.Cells.Count > 1 Then Exit Sub

    If Not Intersect(Target, Range("D17:D1015")) Is Nothing Then
        Target.Offset(ColumnOffset:=1).ClearContents
    End If
End Sub

这应该更快,因为它不需要循环。

答案 1 :(得分:2)

Private Sub Worksheet_Change(ByVal Target As Range)下方输入以下内容

Dim i as long

在使用它之前,您需要定义我是什么。