3

我正在尝试使用 VBA 宏从存储在我的工作表中的列表中设置单元格数据验证。我不知道列表会有多长,所以需要动态选择范围。

目前 .Add Type:= Formula1:="=perfGradeRange" 行正在引发运行时错误“1004”应用程序定义或对象定义错误。

我的代码是这样的:

Sub Perf_Grade_Dropdown()

Dim perfGradeData As Worksheet
Dim usedRange As range
Dim rLastCell As range
Dim range As range
Dim perfGradeRange As range

Set perfGradeData = Worksheets("Values")

perfGradeData.Unprotect Password:="pass"

perfGradeData.Activate

Set rLastCell = perfGradeData.Cells.Find(What:="*", After:=Cells(1, 1),    LookIn:=xlFormulas, LookAt:= _
xlPart, SearchOrder:=xlByRows, SearchDirection:=xlPrevious, MatchCase:=False)

Set perfGradeRange = perfGradeData.range(Cells(1, 1), rLastCell)

Set range = perfGradeData.range(Cells(3, 3), Cells(4, 3))

    With range.Validation
    .Delete
    .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _
    xlBetween, Formula1:="=perfGradeRange"
    .IgnoreBlank = True
    .InCellDropdown = True
    .InputTitle = ""
    .ErrorTitle = ""
    .InputMessage = ""
    .ErrorMessage = ""
    .ShowInput = True
    .ShowError = True
End With

perfGradeData.Protect Password:="pass", DrawingObjects:=True, contents:=True,          Scenarios:=True, userinterfaceonly:=True, _
AllowSorting:=True, AllowFiltering:=True, AllowDeletingColumns:=True,    AllowInsertingColumns:=True
perfGradeData.EnableAutoFilter = True

 End Sub

我已经看到了以下两个问题,但未能得到任何可行的建议:

使用变量时在 excel 中通过 VBA 设置验证失败

当工作表在 MS-Excel 中受到保护时,如何避免运行时错误?

感谢任何帮助。

4

1 回答 1

3

Range 是一个类,所以最好不要将它用于变量名。其次,Formula1:= 需要参数作为字符串,所以我使用了perfGradeRange.Cells(1).

Sub Perf_Grade_Dropdown()

        Dim perfGradeData As Worksheet
        Dim usedRange As range
        Dim rLastCell As range
        Dim rng As range
        Dim perfGradeRange As range

        Set perfGradeData = Worksheets("Values")

        perfGradeData.Unprotect Password:="pass"

        perfGradeData.Activate

        Set rLastCell = perfGradeData.Cells.Find(What:="*", After:=Cells(1, 1), LookIn:=xlFormulas, LookAt:= _
                                                 xlPart, SearchOrder:=xlByRows, SearchDirection:=xlPrevious, MatchCase:=False)

        Set perfGradeRange = perfGradeData.range(Cells(1, 1), rLastCell)

        Set rng = perfGradeData.range(Cells(3, 3), Cells(4, 3))

        With rng.Validation
            .Delete
            .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:=xlBetween, Formula1:=perfGradeRange.Cells(1)
            .IgnoreBlank = True
            .InputTitle = ""
            .ErrorTitle = ""
            .InputMessage = ""
            .ErrorMessage = ""
            .ShowInput = True
            .ShowError = True
        End With


        perfGradeData.Protect Password:="pass", DrawingObjects:=True, contents:=True, Scenarios:=True, userinterfaceonly:=True, _
                              AllowSorting:=True, AllowFiltering:=True, AllowDeletingColumns:=True, AllowInsertingColumns:=True
        perfGradeData.EnableAutoFilter = True

    End Sub
于 2013-07-10T03:27:35.813 回答