2013-11-21 72 views
0

我有一個單元格範圍(B5:B61),我希望在值=「選擇」時添加數據驗證列表,併爲所有其他值添加字符限制=單元格的字符串長度。設置字符限制等於單元格值

該代碼用於添加數據驗證列表和文本長度。但是,如何讓公式2 =單元格的值的字符串長度?

Sub Attribute_Options_Cell_Validation() 

For Each cell In Range("B5:B61").Cells 
    With cell 
     .Formula = "=myformula" 
     .Value = .Value 
     If cell = "Choose" Then 
    With .Validation 
     .Delete 
     .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _ 
     xlBetween, Formula1:="=new_DDM3" 
     .IgnoreBlank = True 
     .InCellDropdown = True 
     .InputTitle = "" 
     .ErrorTitle = "" 
     .InputMessage = "" 
     .ErrorMessage = "" 
     .ShowInput = True 
     .ShowError = True 
     End With 
     Else 
     With .Validation 
     .Delete 
     .Add Type:=xlValidateTextLength, AlertStyle:=xlValidAlertStop, _ 
     Operator:=xlBetween, Formula1:="1", Formula2:="20" 
     .IgnoreBlank = True 
     .InCellDropdown = True 
     .InputTitle = "" 
     .ErrorTitle = "" 
     .InputMessage = "" 
     .ErrorMessage = "" 
     .ShowInput = True 
     .ShowError = True 
End With 
End If 
End With 
Next cell 
End Sub 

回答

1

這個工作對我來說:

Dim maxLen as long 
    '..... 
    maxLen = Len(cell.Value) 
    With cell.Validation 
     .Delete 
     .Add Type:=xlValidateTextLength, AlertStyle:=xlValidAlertStop, _ 
     Operator:=xlBetween, Formula1:="1", Formula2:=maxLen 
     .IgnoreBlank = True 
     .InCellDropdown = True 
     .InputTitle = "" 
     .ErrorTitle = "Entry is too long!" 
     .InputMessage = "Max length: " & maxLen 
     .ErrorMessage = "Please enter no more than " & maxLen & " characters" 
     .ShowInput = True 
     .ShowError = True 
    End With 
+0

完美工作,甚至更好,我明白爲什麼。 – Astr0zombi3s

相關問題