【问题标题】:Can there be if else loop within if else loop in VBA?VBA中的if else循环中是否有if else循环?
【发布时间】:2019-02-09 06:19:12
【问题描述】:
Sub lol_function()

Dim x, y, count, i, mhr, z, allowed, leftover As Integer

For y = 13 To 210
For x = 6 To 1000 Step 8
allowed = 50 * Cells(x, 8)

mhr = Cells(x, 7)
count = count + mhr

If mhr <= allowed And count <= allowed Then
    Cells(x, y).value = mhr

Else
    Cells(x, y).value = allowed + mhr - count
    y = y + 1

    leftover = count - allowed

If leftover <= allowed Then

    Cells(x, y).value = leftover
    count = leftover

Else

    Cells(x, y).value = allowed
    leftover = mhr - allowed
    y = y + 1

End If

Next x, y

End Sub

如果我不使用第二个 if else 循环,那么代码可以正常工作,但使用第二个 if else 语句我不断收到“Next without For”错误。任何帮助将不胜感激。

另外,如果我包含第二端,如果它弄乱了我的代码。我需要它是

if condition
....

else 
....

       if condition
            .....

       else
            .....

end if 

还有其他方法可以在 else 语句中创建循环吗?

【问题讨论】:

  • Next x, y 是一个语法错误(您需要 2 个关闭 Next's),并且它缺少上面一行中的 End IfIndenting the code would make this more obvious.
  • 另外,Dim x, y, count, i, mhr, z, allowed, leftover As Integer 并没有按照您的想法行事。 leftover 是唯一被设置为整数的变量,所有其他变量都是 Variants

标签: excel vba


【解决方案1】:

由于您有两个“If”语句,因此在“Next”语句之前需要第二个“End If”。

【讨论】:

    【解决方案2】:

    您需要在第一个 Else 和第二个 If 语句之间添加 End If

    【讨论】:

      猜你喜欢
      • 2015-10-28
      • 1970-01-01
      • 2019-11-03
      • 1970-01-01
      • 2015-11-13
      • 1970-01-01
      • 2017-08-02
      • 2019-12-04
      • 2022-01-10
      相关资源
      最近更新 更多