【发布时间】:2018-12-24 04:39:06
【问题描述】:
我正在做一个复杂的项目。对于这一步,我试图让一个程序在一定数量的行(我使用 For 循环)内重复一定次数(我试图使用 Do Until 循环) .行数大于(大得多)我希望程序循环的次数。我尝试使用两个循环的原因是因为我想在 i 范围内的每一行中搜索各种条件,但我只想更改前 n 个匹配项。因为我不知道匹配的位置或距离有多远,所以我需要搜索完整的 9000+ 范围。
到目前为止,单独的 for 循环有效,但我不知道如何成功添加 Do Until 循环。我在内部和外部都尝试过 For 循环,但都没有工作。
在本例中,for 循环位于内部。本来应该做 9,结果做了 9057(E 的值):
Sub Hilight()
Dim usch As Worksheet
Set usch = Worksheets("USCH attributes")
Dim m As Worksheet
Set m = Worksheets("Maps")
Dim i As Integer
Dim E As Integer
Dim n As Integer
Dim s1 As String
Dim s2 As String
Dim s3 As String
s1 = Range("U1").Value
s2 = Range("V1").Value
s3 = Range("W1").Value
Dim rU As String
Dim rE As String
Dim rA As String
rU = m.Range("D4").Value
rE = m.Range("D3").Value
rA = m.Range("D2").Value
E = Range("S1").Value
n = 0
Do Until n >= 9
For i = 1 To E
n = n + 1
Debug.Print n
If Cells(i, 15).Value = s3 And Cells(i, 13).Value = rA And Cells(i, 11) = "" Then
Cells(i, 15).Interior.ColorIndex = 0
End If
Next i
Loop
End Sub
我猜,下一个外部带有 for 循环的示例会更好一些?调试只打印了 9 个,所以很好。不幸的是,For 循环似乎根本没有运行,因为没有任何改变颜色。 (只粘贴内部代码,因为所有的暗淡都是一样的)
For i = 1 To E
Do Until n >= 9
n = n + 1
Debug.Print n
If Cells(i, 15).Value = s3 And Cells(i, 13).Value = rA And Cells(i, 11) = "" Then
Cells(i, 15).Interior.ColorIndex = 37
End If
Loop
Next i
我想过将 n = 0 放在循环中,但那只会打印 1 九千次,对吧?
你们能帮我解决这个问题以正常运行吗?我已经阅读循环教程三天了,但我无法让它工作:(非常感谢任何帮助!
【问题讨论】:
-
你能做一些minimal reproducible example吗?并用一句话解释这两个循环应该做什么,最多 20 个单词。
-
i 循环应该在一个范围内搜索匹配项,并且 n 循环应该限制 i 循环迭代的次数。哇,这根本不对,是吗
-
n可能不应该在每个For循环上增加,而只能在(之前)之后增加。我认为你应该使用 2 个For循环,这样最好。
标签: vba excel excel-2010 nested-loops