0

我有一个密码生成器 Sub,我想将其更改为函数并在宏中使用它来生成从 B2 开始的列,之后的每个单元格都是唯一密码。

它唯一做的就是删除我的 B1 Header 单元格。

谢谢

我有子:

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 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
4

2 回答 2

1

You need an extra row in your function, just before End Function:

RandomPassword=strPassword

Otherwise your function will have no value, resulting in empty cell.

于 2013-05-19T19:19:04.493 回答
1

You need to assign the value of strPassword variable to function 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


Also in below procedure you are getting the last used row in column B and then overwriting them with random password. I feel like it you need to get the last used row of column A instead.

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
于 2013-05-19T19:19:49.983 回答