Skip to content

Instantly share code, notes, and snippets.

@DiegoQueiroz
Last active July 29, 2020 19:06
Show Gist options
  • Save DiegoQueiroz/9c77d8ca78d761e5272b28973b730dfc to your computer and use it in GitHub Desktop.
Save DiegoQueiroz/9c77d8ca78d761e5272b28973b730dfc to your computer and use it in GitHub Desktop.
Attribute VB_Name = "GeraDigitosAleatorios"
Option Explicit
Private Declare Function BCryptGenRandom Lib "bcrypt.dll" (ByVal hAlgorithm As Long, ByRef pbBuffer As Long, ByVal cbBuffer As Long, ByVal dwFlags As Long) As Long
Const BCRYPT_USE_SYSTEM_PREFERRED_RNG = &H2
Const STATUS_SUCCESS = &H0
Public Function GeraDigitosAleatorios(ByVal tamanho As Integer) As String
Const ERRO_GERACAO_SEQUENCIA_NUMERO = vbObjectError + 1
Const ERRO_GERACAO_SEQUENCIA_DESCRICAO = "Erro na geração da sequência aleatória"
Dim numero As Long
GeraDigitosAleatorios = ""
While Len(GeraDigitosAleatorios) < tamanho
If STATUS_SUCCESS <> BCryptGenRandom(0, numero, 4&, BCRYPT_USE_SYSTEM_PREFERRED_RNG) Then
Err.Raise Number:=ERRO_GERACAO_SEQUENCIA_NUMERO, _
Description:=ERRO_GERACAO_SEQUENCIA_DESCRICAO
End If
GeraDigitosAleatorios = GeraDigitosAleatorios + CStr(Abs(numero))
Wend
GeraDigitosAleatorios = Right(GeraDigitosAleatorios, tamanho)
End Function
'##################################
' Exemplo de Utilização
'##################################
'Private Sub Command1_Click()
' MsgBox GeraDigitosAleatorios(8)
'End Sub
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment