“继续”变通办法

注:虽然在边界附近,但我认为这个问题更多地落在围栏的“明确答案”一边,而不是“以意见为基础”的一面。

我有以下代码来设置数据validation的单元格范围:

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步骤复制到ElseIfElse语句中,但像其他人一样,我讨厌复制代码:

  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 

我的问题是:

  1. 选项1和选项2在计算上是否等效?
  2. 以这种方式使用GoTo有什么陷阱吗?
  3. 代码序列有更好的select吗?
    • (我可以开始检查子string,然后设置数据validation,然后删除validation,如果以前的单元格是空的,但似乎是在自己的脚射击)。

  1. 你的select1和2似乎做同样的事情(testing应该证实这一点)

  2. 我将GoTo构造看作是stream的中断 – 如果(当)变得更复杂时,将更难debugging

  3. 你是对的 – 复制代码从来没有帮助,但我会简化这样的代码


 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 

  • 不pipeIf分支如何,您都会删除初始validation,所以一开始就这样做
  • 只提取一次偏移值(尽量减less与范围的交互)
  • 如果单元格是空的

    • 移动到下一个单元格(不需要处理)
  • 其他

    • 确定你需要添加什么validation
    • 添加它,继续前进