I am trying to dynamically add validation (using DataValidation:List) to ranges in a worksheet. I recorded a macro that produced the following code:
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
This was working fine for the static range C2:C100, but the column may not be always be C. I have a variable cMANFCM that contains the column number. I tried to edit the code to use this:
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
Why doesn't this work and how do I fix it?
With Worksheets("Clusters").Range("A2:A100").Offset(, cMANFCM-1).ValidationWorksheets("Clusters").Cells(2,cMANFCM).Resize(100,1)Cells()without a qualifying worksheet will always refer to the ActiveSheet, so instead of using (e.g.)sht.Range(Cells(1,1), Cells(100,1))you should usesht.Range(sht.Cells(1,1), sht.Cells(100,1))