将Sub更改为Function,然后在vba中调用

时间:2013-05-19 19:13:03

标签: excel excel-vba vba

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

它唯一能做的就是删除我的B1标题单元格。

由于

我有Sub:

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

2 个答案:

答案 0 :(得分:1)

End Function之前,您需要在函数中添加一行:

RandomPassword=strPassword

否则你的函数没有值,导致空单元格。

答案 1 :(得分:1)

您需要将strPassword变量的值分配给函数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