循环浏览除less数范围内的所有数字

我需要循环通过i = 1到99,但我想跳过几个特定的​​i值。 我想跳过的数字是41,83,87,91,92,93,98

我意识到我可以将我所有的行为都embedded到我i <> 41以内,或者i <> 83 。 也许分配一个variables来包含值跳过一个CSL和使用Split ? 我不知道我的大脑不工作。 请帮忙。

  For i = 1 To 99 If i <> 41 And i <> 83 And i <> 87 And i <> 91 _ And i <> 92 And i <> 93 And i <> 98 Then 'do stuff End If Next i 

宁愿设置一个像这样的variables:

  not_use = "41,83,87,91,92,93,98" 

然后有某种For i = 1 To 99除非在not_use但是根据我所知没有办法写。

抛出我没有在string长度取代没有比较:

 Sub LoopSkip() Dim NotUse As String NotUse = "41,83,87,91,92,93,98" For i = 1 To 99 If Len("," & NotUse & ",") = Len(Replace("," & NotUse & ",", "," & i & ",", "")) Then 'Do Stuff End If Next i End Sub 

您可以使用工作表公式计算expression式:

 not_use$ = "43,83,87,91,92,93,98" For i = 1 To 99 If Application.Evaluate("ISERROR(MATCH(" & i & ",{" & not_use & "},0))") Then '// Do Something End If Next i 

这意味着“testing”一次性评估,而不是使用多个标准或进一步的循环。

与使用Select Case If语句相比,可以使用更紧凑的方式指定要忽略的值:

 For i = 1 To 99 Select Case i Case 41, 83, 87, 91, 92, 93, 98 'Do nothing Case Else 'Do stuff End Select Next 

这是一个非常粗略的例子,但解决你的问题:

 Sub ArrayLoopExample() Dim MyArray As Variant: MyArray = Array(43, 83, 87, 91, 92, 93, 98) For i = 1 To 99 For x = LBound(MyArray) To UBound(MyArray) If i = MyArray(x) Then 'Skip Else 'Some code End If Next x Next i End Sub 

根据下面的评论更新

只是上面的答案已经做了变化

 Dim not_use As Variant, i As Integer not_use = Array(43, 83, 87, 91, 92, 93, 98) ' create an array For i = 1 To 99 If IsError(Application.Match(i, not_use, 0)) Then ' do some cool stuff End If Next 

也许更小的代码。 如果这是有用的。

 not_use = Split("41,83,87,91,92,93,98",",") For i = 1 To 99 If UBound(Filter(not_use,CStr(i))) Then MsgBox i Next 

刚刚意识到你是要求VBA而不是VBScript。 我的错。