注意:虽然接近边界线,但我认为这个问题确实更多地落在围栏的“确定答案”方面,而不是“基于意见的”方面。
我有以下代码为一系列单元格设置数据验证:
For Each Cell In WorkCenterFields
' If previous cell is empty, clear data validation and go to next FOR iteration
If Cell.Offset(0, -1).Value = "" Then
Cell.Validation.Delete
GoTo NextCell
' If previous cell matches this substring, use this list of values
ElseIf InStr(1, Cell.Offset(0, -1), "INDENG", vbTextCompare) = 0 Then
WorkCenterListFormula = "=Sheet0!B2:B11"
' If previous cell contains text but doesn't match the substring, use this list
Else
WorkCenterListFormula = "=Sheet0!C2:C9"
End If
' Add the data validation list to the cell
With Cell.Validation
.Delete
.Add Type:=xlValidateList, Formula1:=WorkCenterListFormula
End With
NextCell:
Next
这很好用,并且具有逻辑意义。但我不喜欢Excel如何强制NextCell:
标签到最左边。也许我只需要处理它。
显而易见的选项2只是将Cell.Validation.Add
步骤复制到ElseIf
和Else
语句中,但与其他人一样,我讨厌重复代码:
For Each Cell In WorkCenterFields
' If previous cell is empty, clear data validation and go to next FOR iteration
If Cell.Offset(0, -1).Value = "" Then
Cell.Validation.Delete
' If previous cell matches this substring, use this list of values
ElseIf InStr(1, Cell.Offset(0, -1), "INDENG", vbTextCompare) = 0 Then
WorkCenterListFormula = "=Sheet0!B2:B11"
' Add the data validation list to the cell
With Cell.Validation
.Delete
.Add Type:=xlValidateList, Formula1:=WorkCenterListFormula
End With
' If previous cell contains text but doesn't match the substring, use this list
Else
WorkCenterListFormula = "=Sheet0!C2:C9"
' Add the data validation list to the cell
With Cell.Validation
.Delete
.Add Type:=xlValidateList, Formula1:=WorkCenterListFormula
End With
End If
Next
我的问题是:
GoTo
是否有任何陷阱?答案 0 :(得分:0)
您的选项1和2似乎在做同样的事情(测试应该确认这一点)
我认为GoTo
构造是流程的中断 - 如果(何时)它变得更复杂,那么调试就会更难
你是对的 - 重复代码永远不会有帮助,但我会像这样简化代码
Dim offsetVal As String
For Each cel In WorkCenterFields
cel.Validation.Delete
offsetVal = cel.Offset(0, -1).Value2
If Len(offsetVal) > 0 Then
If InStr(1, offsetVal, "INDENG", vbTextCompare) = 0 Then
WorkCenterListFormula = "=Sheet0!B2:B11"
Else
WorkCenterListFormula = "=Sheet0!C2:C9"
End If
cel.Validation.Add Type:=xlValidateList, Formula1:=WorkCenterListFormula
End If
Next
如果单元格为空
否则