写一段VBA代码,生成随机表14行,14列 每行与每列数字都是1到14的数字只出现一次
时间: 2023-09-15 11:04:46 浏览: 117
### 回答1:
Sub 随机表14()
Dim S(), A(), N As Integer
N = 14
ReDim S(N, N)
ReDim A(N)For i = 1 To N
A(i) = i
NextFor i = 1 To N
For j = 1 To N
Randomize
N = Int((N - 1 + 1) * Rnd + 1)
S(i, j) = A(N)
A(N) = A(N - 1)
N = N - 1
Next
NextFor i = 1 To N
For j = 1 To N
Cells(i, j) = S(i, j)
Next
NextEnd Sub
### 回答2:
以下是使用VBA语言编写的代码,可以生成一个14行14列的随机表格,其中每一行和每一列的数字都是1到14的数字且只出现一次:
```vba
Sub GenerateRandomTable()
Dim arr(1 To 14, 1 To 14) As Integer ' 定义一个14行14列的整数数组
Dim i As Integer, j As Integer
Dim num As Integer
' 初始化数组
For i = 1 To 14
For j = 1 To 14
arr(i, j) = 0
Next j
Next i
' 生成随机表格
For i = 1 To 14
For j = 1 To 14
Do
num = Int((14 * Rnd) + 1) ' 生成1到14的随机整数
Loop Until arr(i, num) = 0 ' 检查该数字是否已经出现过
arr(i, num) = j ' 将数字赋值给表格
Next j
Next i
' 输出随机表格
For i = 1 To 14
For j = 1 To 14
Cells(i, j).Value = arr(i, j)
Next j
Next i
End Sub
```
请将以上代码复制到一个新的VBA模块中,然后运行`GenerateRandomTable`子过程,即可在Excel表格中生成一个满足要求的随机表格。
### 回答3:
下面是一段可以生成随机表格的VBA代码:
```vba
Sub GenerateRandomTable()
Dim tableArr(1 To 14, 1 To 14) As Integer
Dim rowArr(1 To 14) As Integer
Dim colArr(1 To 14) As Integer
Dim i As Integer, j As Integer, k As Integer
' 初始化行数组和列数组
For i = 1 To 14
rowArr(i) = i
colArr(i) = i
Next i
' 生成随机表格
For i = 1 To 14
For j = 1 To 14
k = Int((15 - j) * Rnd + 1) ' 随机生成1到15-j的整数
tableArr(i, j) = colArr(k)
' 调整列数组
For k = k To 13
colArr(k) = colArr(k + 1)
Next k
Next j
' 调整行数组
For k = i To 13
rowArr(k) = rowArr(k + 1)
Next k
Next i
' 输出随机表格到工作表
For i = 1 To 14
For j = 1 To 14
Cells(i, j) = tableArr(i, j)
Next j
Next i
End Sub
```
这段VBA代码使用了一个二维数组`tableArr`来存储随机生成的表格。同时,使用两个一维数组`rowArr`和`colArr`分别存储行和列数字的备选项。在生成随机表格的过程中,随机选择一列数字,并移除对应的备选项。最后,将生成的随机表格输出到工作表中的14行14列。
阅读全文