【问题标题】:If statement to skip items in For loop by checking variable's existence in an Array of numbersIf 语句通过检查变量在数字数组中的存在来跳过 For 循环中的项目
【发布时间】:2019-01-09 02:51:10
【问题描述】:

经过长时间的搜索,我无法找到我的问题的有效答案,所以这是我最后的选择。

我有一个循环遍历数组的 For 语句。但是我希望循环跳过数组中特定点的项目。

到目前为止,这是我的代码:

Public Sub test ()

Dim FArray(10, 1) As String
Dim Supported() As Variant

Supported = Array(2, 4, 5)

'Functional Text
FArray(0, 0) = "B30"
FArray(0, 1) = "B3"
'Functional Audio
FArray(1, 0) = "B31"
FArray(1, 1) = "B17"
'PS Text
FArray(2, 0) = "B33"
FArray(2, 1) = "B4"
'PS Audio
FArray(3, 0) = "B34"
FArray(3, 1) = "B18"
'Advanced V2 Text
FArray(4, 0) = "B36"
FArray(4, 1) = "B5"
'Advanced V2 Audio
FArray(5, 0) = "B37"
FArray(5, 1) = "B19"
'Cus Text
FArray(6, 0) = "B39"
FArray(6, 1) = "B6"
'Cus Audio
FArray(7, 0) = "B40"
FArray(7, 1) = "B20"
'Implicit
FArray(8, 0) = "B42"
FArray(8, 1) = "B7"
'OOD
FArray(9, 0) = "B44"
FArray(9, 1) = "B8"
'OOD Audio
FArray(10, 0) = "B45"
FArray(10, 1) = "B21"

For I = LBound(FArray) To UBound(FArray)
    If I = LBound(Supported) To Ubound(Supported) Then

    Else

    idsource = FArray(I, 1)
    OutputCell = FArray(I, 0)
    'Debug.Print (idsource)
    'Debug.Print (OutputCell)

    Call DLResults_generic(idsource, OutputCell)

    End If

Next I

如您所见,我使用变量“I”启动了一个 For 循环,然后我使用第二个数组(支持)来标记我希望 for 循环跳过的点。我可以这样做:

If I = 2 Or I = 4 Or I = 5 Then

但我想要一些更容易更改的东西,这样我就可以进入支持的数组并输入新值。

如果有人能帮我找到一种说法“如果‘我’在受支持的数组中,请跳过 For 循环中的此项”,我将不胜感激

谢谢!

【问题讨论】:

  • 听起来您需要在 for 循环中使用 continue;,尝试查找有关如何使用它的信息。
  • @steven vba 中没有continue;
  • 是的,我刚刚通过搜索自己注意到了这一点,我偶然发现了这个帖子,也许这是一个不错的替代品:stackoverflow.com/questions/5895908/continue-for-loop
  • 可以构建一个用户函数来检查该值是否是数组的一部分,试试看stackoverflow.com/questions/38267950/…
  • 未经测试但可能是if isnumeric(application.match(I,Supported,0)) then

标签: arrays vba excel if-statement


【解决方案1】:

我会将Supported 设为字典,这样您就不必每次都对其进行迭代以找出其中是否包含值:

Set Supported = CreateObject("Scripting.Dictionary") 
Supported.Add 2, True
Supported.Add 3, True
Supported.Add 5, True

然后是你的循环:

For I = LBound(FArray) To UBound(FArray)
    If Not Supported.Exists(I) Then
        idsource = FArray(I, 1)
        ' ... etc ... 
    End If
Next I

【讨论】:

  • 这是一个优雅的解决方案,我没想到,非常感谢!
猜你喜欢
  • 1970-01-01
  • 2014-07-20
  • 1970-01-01
  • 2022-06-30
  • 1970-01-01
  • 1970-01-01
  • 2022-07-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多