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

我正在尝试dynamic添加validation (使用DataValidation:List)在工作表中的范围。 我logging了一个生成以下代码的macros:

 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.我有一个包含列号的variablescMANFCM。 我试图编辑代码来使用这个:

 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 

为什么不这样做,我该如何解决?

你的代码在我的工作 – 我已经添加一行删除所有现有的validation,它确实创build新的validation,而不会引发错误:

很多validation参数可能会被忽略…而且当其他工作表处于活动状态时,您可以select如何引用表单/范围:

 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