簡體   English   中英

如何使用 VBA 在 Excel 的 5 列中獲得“是”和“否”的排列?

[英]How to use VBA to get permutations of “yes” and “No” across 5 columns in Excel?

我需要在五列中列出是/否的所有排列。 例如,{是,是,是,是,是},{是,是,是,是,否},{是,是,是,否,否},{是,是,否,否,否}等...看這個截圖

問題是我只想出了那幾個,我認為總數是 120... 是否有一些 VBA 代碼我可以運行以獲得所有排列?

您不需要 VBA 來執行此操作。 以下工作表公式可助您實現目標。

Select 單元格B2並粘貼此公式:

=CHOOSE(1+MID(LEFT("00000",5-LEN(DEC2BIN(32-ROW()+1)))&DEC2BIN(32-ROW()+1),COLUMN()-1,1),"No","Yes")

現在將該公式復制到此范圍: B2:F33

而已。

當然,之后,您可能希望復制結果並粘貼為值以在單元格中而不是公式中具有硬值。


如果您更喜歡編碼解決方案,這里是如何在 VBA 中執行此操作:

Option Explicit

Sub DisplayYesNoPerms()
    Dim rows&, cols&
    cols = 5
    rows = 2 ^ cols
    [b2].Resize(rows, cols) = YesNoPerms(rows, cols)
End Sub

Function YesNoPerms(rows&, cols&)
    Dim i&, j&, t$, v
    ReDim v(0 To rows - 1, 1 To cols)
    For i = 0 To rows - 1
        t = Format(DecToBin(i), String(cols, "0"))
        For j = 1 To cols
            v(i, j) = IIf(Mid(t, j, 1), "No", "Yes")
        Next
    Next
    YesNoPerms = v
End Function

Function DecToBin$(ByVal n&)
    Do
        DecToBin = n Mod 2 & DecToBin
        n = n \ 2
    Loop While n
End Function

我不會為您提供 VBA 解決方案,而是您可以實現的算法:只需將每個“否”視為數字 0,將“是”視為數字 1。您在二進制系統中創建所有數字,從“00000”到“11111”(所以從0到31)。

所以,你需要做的是:

You take every number from 0 to 31, and for every number:
  You convert it into binary format.
  In that binary format, replace every 0 by a "No" and every 1 by a "Yes".
  Find a way to fill your Excel sheet with the corresponding results.

祝你好運

這應該將所有組合打印到相應的行/列。 用戶需要 select header 正下方的左上角單元格。

Dim i As Long, ii As Long, iii As Long, iiii As Long, iiiii As Long
Dim j As Long, jj As Long
Dim str As String
Dim rng As Range
Dim arr(1) As String
arr(0) = "yes"
arr(1) = "no"
Dim arr_rows() As String
Dim arr_columns() As String

' five nested loops (each for a column)
' the idea is to have all possibilities (yes or no) covered
' each row is taken care of by adding vbNewLine
For i = LBound(arr) To UBound(arr)
 For ii = LBound(arr) To UBound(arr)
  For iii = LBound(arr) To UBound(arr)
   For iiii = LBound(arr) To UBound(arr)
    For iiiii = LBound(arr) To UBound(arr)
     str = str & arr(i) & "," & arr(ii) & "," & arr(iii) & "," & arr(iiii) & "," & arr(iiiii) & vbNewLine
    Next iiiii
   Next iiii
  Next iii
 Next ii
Next i

' splitting the string created in the loop by new line character
' (i.e. obtaining an array with an element for each row)
' for each row splitting by a comma
' (i.e. obtaining another array with an element for each column)
arr_rows = Split(str, vbNewLine)
Set rng = Selection
For j = LBound(arr_rows) To UBound(arr_rows)
    arr_columns = Split(arr_rows(j), ",")
    For jj = LBound(arr_columns) To UBound(arr_columns)
        rng.Offset(j, jj) = arr_columns(jj)
    Next jj
Next j

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM