如何在Excel中生成或列出所有可能的排列组合?
排列组合可以定义为对象按特定顺序的排列。在本文中,用户将了解使用VBA代码生成排列组合的方法。为此,用户需要打开VBA代码编辑器,然后只需点击“确定”按钮。最后,运行编写的代码,排列组合序列将正常显示在工作表上。请参考所有列出的步骤,以了解完整的方法。
示例 1:使用 VBA 代码在 Excel 中生成或列出所有可能的排列组合
步骤 1
了解在 Excel 中生成所有可能的排列组合的过程。在本例中,用户将能够使用 VBA 代码计算所有可能的排列组合。
请考虑以下工作表:
步骤 2
转到“开发工具”选项卡,然后在“代码”部分转到“Visual Basic”选项卡。请参考下图以获得正确的参考:
步骤 3
新打开的对话框是“Microsoft Visual Basic for Applications”。这将打开以下代码窗口:
步骤 4
在对话框中,打开“插入”选项,然后点击“模块”。请参考下图以获得参考
步骤 5
这将打开一个空白代码区域:
步骤 6
在编辑器中键入以下代码:
' define function header
Sub Evaluating_String()
'Declaring required variables
Dim str_x As String
Dim row_f As Long
Dim sc_x As Boolean
' setting required parameter values
sc_x = Application.ScreenUpdating
Application.ScreenUpdating = False
' message to display for dialog box
str_x = Application.InputBox("Enter text to permute:", "Input dialog box", , , , , , 2)
' if length of entered string is less than 2
' then exist the sub
If Len(str_x) < 2 Then Exit Sub
' if len is greater than 8, then
If Len(str_x) >= 8 Then
' print message for too many premutations
MsgBox "Please eneter less than 8 word combination!!!!!", vbInformation, "Input dialog box"
Exit Sub
' else block
Else
'clear column 1 data
ActiveSheet.Columns(1).Clear
'set 1 to row_f value
row_f = 1
' calling GetPermutation
Call GetPermutation("", str_x, row_f)
End If
Application.ScreenUpdating = sc_x
End Sub
' defining submodule
Sub GetPermutation(str_1 As String, str_2 As String, ByRef row_x As Long)
Dim i As Integer, len_x As Integer
' calculating the required length
len_x = Len(str_2)
' if expression
If len_x < 2 Then
' calculating range data
Range("A" & row_x) = str_1 & str_2
row_x = row_x + 1
' else block
Else
' for each block
For i = 1 To len_x
' calling permutation
Call GetPermutation(str_1 + Mid(str_2, i, 1), Left(str_2, i - 1) + Right(str_2, len_x - i), row_x)
Next
End If
End Sub
代码区域的快照如下所示:
为了确保结果正确执行,请注意正确的语法和代码缩进。
步骤 7
点击以下所示的“运行”按钮:
步骤 8
之后,一个名为“宏”的新对话框显示上面声明的模块名称。
步骤 9
这将打开“输入对话框”,其中包含一个输入标签。用户可以输入想要创建排列组合的数据。
步骤 10
键入数据为“A2#”,然后点击“确定”。
步骤 11
这将显示如下所示的可能的排列组合:
结论
完成本文后,用户将能够使用 VBA 代码从提供的字符串数据生成排列组合序列。使用 VBA 代码时唯一需要考虑的事实是使用正确的语法来执行提供的代码语句,并按照上述说明编写正确的代码。在本例中,将 3 个字符传递给字符串,获得的结果数量为 $\mathrm{2^{3}\:=\:6}$。
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP