MS Access Visual Basic - 在文本字段中生成随机字符串

时间:2014-03-25 09:28:38

标签: vba ms-access access-vba

我们在使用Microsoft Access运行的公司中拥有旧软件(由多年前的第一批员工制作)。老板让我在点击的特定文本框中添加随机字符串生成但我不知道如何做到这一点。我没有任何Microsoft Access编程经验,这就是为什么我要求你提供帮助。

到目前为止,我设法创建了按钮和文本字段。多数民众赞成在哪里停止。我还设法访问了按钮操作的代码:

Private Sub command133_Click()

End Sub

3 个答案:

答案 0 :(得分:11)

这是一种方法,可以在Access VBA(比vb.net更老的基础)中运行。它将生成一个包含字母和数字的字符串。

Sub test()

    Dim s As String * 8 'fixed length string with 8 characters
    Dim n As Integer
    Dim ch As Integer 'the character
    For n = 1 To Len(s) 'don't hardcode the length twice
        Do
            ch = Rnd() * 127 'This could be more efficient.
            '48 is '0', 57 is '9', 65 is 'A', 90 is 'Z', 97 is 'a', 122 is 'z'.
        Loop While ch < 48 Or ch > 57 And ch < 65 Or ch > 90 And ch < 97 Or ch > 122
        Mid(s, n, 1) = Chr(ch) 'bit more efficient than concatenation
    Next

    Debug.Print s

End Sub

答案 1 :(得分:1)

尝试此功能:

Public Function GetRandomString(ByVal iLength As Integer) As String
    Dim sResult As String = ""
    Dim rdm As New Random()

    For i As Integer = 1 To iLength
        sResult &= ChrW(rdm.Next(32, 126))
    Next

    Return sResult
End Function

答案 2 :(得分:0)

在@Bathsheba代码上工作,我做到了这一点。它会生成一个随机字符串,其中包含您想要的字符数。

代码:

Public Function GenerateUniqueSequence(numberOfCharacters As Integer) As String

    Dim random As String  ' * 8 'fixed length string with 8 characters
    Dim j As Integer
    Dim ch As Integer   ' each character

    random = ""

    For j = 1 To numberOfCharacters
        random = random & GenerateRandomAlphaNumericCharacter
    Next

    GenerateUniqueSequence = random

End Function

Public Function GenerateRandomAlphaNumericCharacter() As String

    'Numbers : 48 is '0', 57  is '9'
    'LETTERS : 65 is 'A', 90  is 'Z'
    'letters : 97 is 'a', 122 is 'z'

    GenerateRandomAlphaNumericCharacter = ""

    Dim i As Integer

    Randomize
    i = (Rnd() * 2) + 1 'One chance out of 3 to choose one of 3 catégories

    Randomize
    Select Case i
        Case 1 'Numbers
            GenerateRandomAlphaNumericCharacter = Chr(Rnd() * 9 + 48)
        Case 2 'LETTERS
            GenerateRandomAlphaNumericCharacter = Chr(Rnd() * 25 + 65)
        Case 3 'letters
            GenerateRandomAlphaNumericCharacter = Chr(Rnd() * 25 + 97)
    End Select

End Function

我使用随机数字的字符,如下所示:

'Generates random Session ID between 15 and 30 alphanumeric characters
SessionID = GenerateUniqueSequence(Rnd * 15 + 15)

结果:

  

s8a8qWOmoDvC4jKRjPr5hOY12u 26
  TB24qZ4cNfr6EdyY0J 18
  6LZRQ9P5WHLNd71LIdqJ 20
  KPN0RmlhhJKnVzPTkW 18
  R2pNOKWJMKl9KpSoIV2egUNTEb1QC2 30
  X8jHuupP6SvEI8Dt2wJi 20