应用程序 Visual Basic/伪随机字符表
外观
此代码模块适用于 MS Excel。它在 Sheet1 上创建了一个伪随机字符、整数和大写字母表。每次运行该过程时,都会创建一个新的不同表格。
- 将代码复制到 Excel 中的标准 VBA 模块中,然后运行过程 MakePseudoRandomTable() 来创建表格。如所示,Sheet1 将被覆盖。
- 输出使用等宽字体 Consolas,以获得最清晰的布局和类型。除了确保垂直和水平的整齐布局之外,等宽表格允许对角线读取序列,从而极大地扩展了它们的实用性。
- 通过更改代码标题中的值 nRows 和 nCols 来调整表格的大小,如果需要,可以插入要使用的表的名称。该代码将添加编号的行和列标题,并将这些标题添加到显示或打印的每个页面。
- 如果需要确切的列数和行数,请调整工作表的页边距,以及可能调整字体大小,直到获得所需的结果。
- 整数与大写字母的比例仅为 10/36,但只需稍加努力即可轻松更改代码中的比例。
Option Explicit
Sub MakePseudoRandomTable()
' Makes a pseudo random table of integers and capitals
' using VBA internal function Rnd().
'NOTES
' User should set narrow margins for best use of page.
' This will give about 47 rows by 35 cols
' Numbered headings are set to repeat on each printed page.
' Set number of rows and columns below.
' Integers to capitals ratio approx 10:26 = 0.385.
' Enter "0-127" in VBA Help for link to ASCI code numbers.
Dim sht As Worksheet, sStr As String
Dim nX As Integer, nAsc As Integer
Dim nRows As Long, nCols As Long
Dim nR As Long, nC As Long
'set required table size and worksheet name here
nRows = 100 'number of rows
nCols = 100 'number of columns
Set sht = ThisWorkbook.Worksheets("Sheet1")
sht.Activate
'clear and format worksheet
With sht.Columns
.ClearContents
.ClearFormats
.HorizontalAlignment = xlCenter
.Font.Name = "Consolas" 'monospaced
.Font.Size = 12
.ColumnWidth = 2
End With
Randomize Timer 'seed system timer
For nR = 1 To nRows 'row loop
For nC = 1 To nCols 'col loop
'allow break commands
DoEvents
'choose integer between 1 and 36 (total number of characters)
nX = Int((36 - 1 + 1) * Rnd + 1)
'make asci numbers in a decided proportion
'set nX<=18 And nX>=1 here for equal integers and capitals
If nX <= 10 And nX >= 1 Then 'for 10:26
nAsc = Int((57 - 48 + 1) * Rnd + 48) 'integers 48 to 57
Else
nAsc = Int((90 - 65 + 1) * Rnd + 65) 'capitals 65 to 90
End If
'convert asci number to string
sStr = Chr(nAsc)
'print single string character per cell
sht.Cells(nR, nC).Value = sStr
Next nC
Next nR
'add numbers to column headings
For nC = 1 To nCols
sht.Cells(1, nC) = nC
Next nC
'set size and orientation of column headings
With sht.Rows(1)
.Font.Size = 12
.Orientation = 90 'vertical
End With
'add numbers to row headings
For nR = 1 To nRows
sht.Cells(nR, 1) = nR
Next nR
'set size of row headings
With sht.Columns(1)
.Font.Size = 12
End With
'print row and col headings on every page
Application.PrintCommunication = False
With ActiveSheet.PageSetup
.PrintTitleRows = "$1:$1"
.PrintTitleColumns = "$A:$A"
End With
Application.PrintCommunication = True
'select first cell
sht.Cells(1, 1).Select
End Sub