将Sub更改为Function,然后以vba调用
我有一个密码生成器Sub,我想将其更改为一个函数,并使用它在macros中生成一个B2列开始每个单元格后是一个唯一的密码。
它唯一的做法是删除我的B1标题单元格。
谢谢
我有小组:
Sub RandomPassword() Dim i As Integer For i = 1 To 8 If i Mod 2 = 0 Then strPassword = Chr(Int((122 - 48 + 1) * Rnd + 48)) & strPassword Else strPassword = Int((9 * Rnd) + 1) & strPassword End If Next i MsgBox strPassword End Sub
我的尝试,并将其转变为一个function:
Function RandomPassword(strPassword As String) As String Dim i As Integer For i = 1 To 8 If i Mod 2 = 0 Then strPassword = Chr(Int((122 - 48 + 1) * Rnd + 48)) & strPassword Else strPassword = Int((9 * Rnd) + 1) & strPassword End If Next i End Function
我的呼唤:
Sub qqq() Dim rng As range Dim lastRow As Long With Sheets("sheet1") lastRow = .range("B" & .Rows.Count).End(xlUp).Row End With For Each rng In Sheets("Sheet1").range("B2:B" & lastRow) rng.Value = RandomPassword(rng.Value) Next End Sub
您需要将strPassword
variables的值分配给函数RandomPassword
Function RandomPassword(ByVal strPassword As String) As String Dim i As Integer For i = 1 To 8 If i Mod 2 = 0 Then strPassword = Chr(Int((122 - 48 + 1) * Rnd + 48)) & strPassword Else strPassword = Int((9 * Rnd) + 1) & strPassword End If Next i RandomPassword = strPassword End Function
同样在下面的过程中,您将获得column B
最后使用的行,然后用随机密码覆盖它们。 我觉得你需要得到column A
的最后使用的行。
Sub qqq() Dim rng As range Dim lastRow As Long With Sheets("sheet1") lastRow = .range("A" & .Rows.Count).End(xlUp).Row End With For Each rng In Sheets("Sheet1").range("B2:B" & lastRow) rng.Value = RandomPassword(rng.Value) Next End Sub
在函数中需要一个额外的行,就在End Function
之前:
RandomPassword=strPassword
否则你的函数将没有值,导致空单元格。