我有一系列单元格(B5:B61),我想在值=“选择”时添加数据验证列表,并为所有其他值添加字符限制=单元格的字符串长度。
该代码用于添加数据验证列表和文本长度。但是如何使formula2 =单元格值的字符串长度?
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
答案 0 :(得分: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