生成随机代码 - 混合数字和字母

问题描述 投票:0回答:1

我想使用userform记录用户数据。

enter image description here

在第一个文本框中,我将插入用户名。 第二个文本框是他们的ID。

在第三个文本框中,我想通过单击“生成”按钮生成一个5个字符的ID /代码(混合数字和字母)(但我不知道编码是什么)。

点击“添加用户”后,我希望在Excel表格中填充数据。我想在列A中插入数字1,2,3 ...,在列B中插入今天的日期(当添加用户详细信息时),然后在列C,D和E中的用户表单中添加数据。

这是我想要的数据:

data example

这是我从网站上复制的代码。

Private Sub CommandButton2_Click()

Dim iRow As Long
Dim ws As Worksheet
Set ws = Worksheets("Database")

'find first empty row in database
iRow = ws.Cells.Find(What:="*", SearchOrder:=xlRows, _
SearchDirection:=xlPrevious, LookIn:=xlValues).Row + 1

'check for a Name number
If Trim(Me.TextBox1.Value) = "" Then
    Me.TextBox1.SetFocus
    MsgBox "Please complete the form"
    Exit Sub
End If

'copy the data to the database
ws.Cells(iRow, 1).Value = Me.TextBox1.Value
ws.Cells(iRow, 2).Value = Me.TextBox2.Value
ws.Cells(iRow, 3).Value = Me.TextBox3.Value

MsgBox "Data added", vbOKOnly + vbInformation, "Data Added"

'clear the data
Me.TextBox1.Value = ""
Me.TextBox2.Value = ""
Me.TextBox3.Value = ""
Me.TextBox1.SetFocus

End Sub
excel vba random userform
1个回答
0
投票

这将生成五个字符的随机数字和字母串。您可以指定按钮并输出到表单而不是消息框。

Sub x()

Dim vOut(1 To 5), i As Long, n As Long

Randomize

For i = 1 To 5
    n = WorksheetFunction.RandBetween(1, 2)
    If n = 1 Then
        vOut(i) = WorksheetFunction.RandBetween(0, 9)
    Else
        vOut(i) = Chr(64 + WorksheetFunction.RandBetween(1, 26))
    End If
Next i

MsgBox Join(vOut, "")

End Sub
© www.soinside.com 2019 - 2024. All rights reserved.