为什么我的循环没有遍历所有值?

时间:2020-08-05 15:58:59

标签: excel vba for-loop

我正在尝试使Excel vba宏正常工作。我正在使用的代码如下:


Dim foo, bar, toto As Double
Dim nb As Integer
nb = 1

For bar = 1 To 1 Step 0.2
For toto = 1 To 4 Step 0.2
For foo = 1 To 2 Step 0.2
    Cells(nb, 1).Value = CStr("bar " & bar & " toto " & toto & " foo " & foo)
    nb = nb + 1
Next foo
Next toto
Next bar
End Sub

我希望看到印有toto = 4的案件。我得到的最终结果是:

bar 1 toto 1 foo 1
bar 1 toto 1 foo 1.2
bar 1 toto 1 foo 1.4
[....]
bar 1 toto 3.8 foo 1.6
bar 1 toto 3.8 foo 1.8
bar 1 toto 3.8 foo 2

变量foo从1到2正常运行,并且每次递增0.2。 另一方面,toto变量从1变为3.8,而不是4。

如何更改我的代码以使toto达到4? 我尝试将for循环的上限值更改为(最大值+ 1步),并且forto起作用,但是对于foo和bar来说,这是一个“额外”循环。

我试图将代码更改为基于时间的方法,但也没有成功。

bar = 1
toto = 1
foo = 1
nb = 1

While (bar <= 1)
toto = 1
    While (toto <= 4)
    foo = 1
        While (foo <= 2)
        
        Cells(nb, 4).Value = CStr("bar " & bar & " toto " & toto & " foo " & foo)
        nb = nb + 1
        foo = foo + 0.2
        Wend
    toto = toto + 0.2
    Wend
bar = bar + 0.2
Wend

2 个答案:

答案 0 :(得分:4)

这是由于浮点错误。我会避免使用Step 0.2,而是在循环内将foobartoto乘以0.2,而在循环时仅使用整数:

Dim foo As Long, bar As Long, toto As Long, nb As Long

nb = 1

For bar = 1 To 5
    For toto = 1 To 20
        For foo = 1 To 10
            Cells(nb, 1).Value = CStr("bar " & bar * 0.2 & " toto " & toto * 0.2 & " foo " & foo * 0.2)
            nb = nb + 1
        Next
    Next
Next

还要注意,在中,Dim foo, bar, toto As Double仅将toto声明为DoublefoobarVariant

答案 1 :(得分:0)

您错误地声明了变量。您需要在每个声明上使用As语句。您这样做的方式使foobar的类型为Variant,这可能是VBA当时想要的。最好每行有一个声明。如果我们使鞋面稍大于4,例如4.01,则它起作用。我不确定为什么。

Dim foo As Double
Dim bar As Double 
Dim toto As Double
Dim nb As Integer
nb = 1

For bar = 1 To 1 Step 0.2
    For toto = 1 To 4.01 Step 0.2
        For foo = 1 To 2 Step 0.2
            Cells(nb, 1).Value = CStr("bar " & bar & " toto " & toto & " foo " & foo)
            nb = nb + 1
        Next foo
    Next toto
Next bar

如果您不喜欢在toto的上限上增加一些斜率,也可以使用Round强制使用有效数字。

这是您期望的方式:

Sub test()
    Dim foo As Single
    Dim bar As Single
    Dim toto As Single
    Dim nb As Integer
    nb = 1
    
    For bar = 1 To 1 Step 0.2
        For toto = 1 To 4 Step 0.2
            toto = Round(toto, 1)
            For foo = 1 To 2 Step 0.2
                Debug.Print CStr("bar " & bar & " toto " & toto & " foo " & foo)
                nb = nb + 1
            Next foo
        Next toto
    Next bar
End Sub