2015-11-26 99 views
4

我有兩個布爾變量,即「a」和「b」。「For」循環的布爾變量?

一般來說,變量有四種狀態(TT,TF,FT,FF)。

我想看看我可以自動將變量從真到假更改爲每個狀態的代碼。

有點像「For」循環,但對於布爾型變量。

For a = True to False 

    For b = True to False 

    Next 
Next 
+2

CBool​​將(-1)= TRUE; CBool​​(0)= False。基本上不是這樣嗎? – DanL

回答

2

您只需表示布爾值1或0,如:

Dim b1 As Byte 
Dim b2 As Byte 
Dim a As Boolean 
Dim b As Boolean 

For b1 = 0 To 1 
    For b2 = 0 To 1 
     a = CBool(b1) 
     b = CBool(b2) 
    Next 
Next 
1

你只需要一個循環:

Dim a As Boolean 
Dim b As Boolean 
Dim i As Integer 

For i = 0 To 3 
    a = i And 1 
    b = i And 2 
    ... 
Next 
0

此:

Do 
    a = CBool(Not a) 
    b = CBool(IIf(a, Not b, b)) 
Loop Until Not a And Not b 

威爾產生全部4個結果,然後退出

+0

改進建議:不需要已布爾值的CBool​​變量:-) – DanL

+0

我沒有將它們聲明爲布爾值:)如果將'CBool​​()'取出,那麼它們被推斷爲'Variant/Interger'顯然,如果你明確聲明爲'布爾',那麼不需要 –

+0

是真的,但你的代碼假定它們是。例如,你不能'不'是一個字符串。 – DanL

1

這是最好的解決方案,我已經找到了VBA保持與原來的代碼的一致性:

Dim a As Boolean 'defining your Boolean Variables 
Dim b As Boolean 

For i = 1 To 0 Step -1: a = i 'this take 'a' from TRUE to FALSE 
    For j = 1 To 0 Step -1: b = j 'this take 'b' from TRUE to FALSE 

    Next j 
Next i