Excel VBA - 使用单元格引用范围

时间:2013-02-27 22:21:17

标签: excel vba excel-vba

我正在尝试将validation(使用DataValidation:List)动态添加到工作表中的范围。我录制了一个生成以下代码的宏:

With Worksheets("Clusters").Range("C2:C100").Validation
    .Delete
    .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _
    xlBetween, Formula1:="=Managers"
    .IgnoreBlank = True
    .InCellDropdown = True
    .InputTitle = ""
    .ErrorTitle = ""
    .InputMessage = ""
    .ErrorMessage = ""
    .ShowInput = True
    .ShowError = True
End With


这对于静态范围C2:C100工作正常,但列可能不总是C.我有一个包含列号的变量cMANFCM。我尝试编辑代码以使用它:

With Worksheets("Clusters").Range(Cells(2,cMANFCM), Cells(100, cMANFCM)).Validation
    .Delete
    .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _
    xlBetween, Formula1:="=Managers"
    .IgnoreBlank = True
    .InCellDropdown = True
    .InputTitle = ""
    .ErrorTitle = ""
    .InputMessage = ""
    .ErrorMessage = ""
    .ShowInput = True
    .ShowError = True
End With


为什么这不起作用?如何解决?

1 个答案:

答案 0 :(得分:1)

您的代码适用于我 - 我添加了一行来删除所有现有的验证,它确实创建了新的验证而不会抛出错误:

许多验证参数可能会被忽略......并且您可以选择在其他工作表处于活动状态时如何引用工作表/范围:

Option Explicit
Sub control()
    'Call changeValidation(4)
    'Call changeValidationPAlbert(5)
    Call changeValidationTWilliams(6)
End Sub

Sub changeValidation(cMANFCM As Integer)

With Excel.ThisWorkbook.Worksheets("Clusters")
    .Cells.Validation.Delete
    .Range(.Cells(2, cMANFCM), .Cells(100, cMANFCM)).Validation.Add _
            Type:=xlValidateList, _
            AlertStyle:=xlValidAlertStop, _
            Operator:=xlBetween, _
            Formula1:="=managers"
End With

End Sub
Sub changeValidationAlbert(cMANFCM As Integer)

With Excel.ThisWorkbook.Worksheets("Clusters")
    .Cells.Validation.Delete
    .Range("A2:A100").Offset(, cMANFCM - 1).Validation.Add _
            Type:=xlValidateList, _
            AlertStyle:=xlValidAlertStop, _
            Operator:=xlBetween, _
            Formula1:="=managers"
End With

End Sub
Sub changeValidationTWilliams(cMANFCM As Integer)

With Excel.ThisWorkbook.Worksheets("Clusters")
    .Cells.Validation.Delete
    .Cells(2, cMANFCM).Resize(100, 1).Validation.Add _
            Type:=xlValidateList, _
            AlertStyle:=xlValidAlertStop, _
            Operator:=xlBetween, _
            Formula1:="=managers"
End With

End Sub