如何在宏中传递参数?

时间:2019-05-25 18:03:57

标签: excel vba

我将以下功能称为

Dim SheetName As String
Dim FirstName As String, LastName As String
FirstName = "Patricia "
LastName = "Katts"
SheetName = GetFullName(FirstName, LastName)


Private Function GetFullName$(First As String, Last As String)
Dim FName As String
Sheets.Add
ActiveSheet.Name = _
WorksheetFunction.Text(FName)
FName = First & Last    
GetFullName = FName
End Function

但出现编译错误:参数非可选。这段代码有什么问题。我不明白。

1 个答案:

答案 0 :(得分:2)

您在此处缺少参数:WorksheetFunction.Text(Value, Format_Text)

但是您不需要工作表功能,可以使用ActiveSheet.Name = fName来更改操作顺序。它将以当前顺序求值为vbNullString

这应该可以正常工作:

Sheets.Add
FName = First & Last    
ActiveSheet.Name = FName
GetFullName = FName

您可能期望.Text做一些本不该做的事情。您可能需要返回工作表,然后在编辑栏中键入“ = text(”)并阅读工具提示。

我不确定您的示例顶部发生了什么。您可以在函数中很好地接收参数,但不会从任何地方传递它。也许我只是对您的格式感到困惑。

这些必须在子,函数或属性中,并且不能像您拥有的那样公开显示。

Dim SheetName As String
Dim FirstName As String, LastName As String
FirstName = "Patricia "
LastName = "Katts"
SheetName = GetFullName(FirstName, LastName)

类似这样的东西

Sub PassingToFunction()

Dim SheetName As String
Dim FirstName As String, LastName As String
FirstName = "Patricia "
LastName = "Katts"
SheetName = GetFullName(FirstName, LastName)

End Sub

我从字面上复制并粘贴了您的示例。进行了我建议的修改,并且可以正常工作。

Sub WorksJustFine()
    Dim SheetName As String
    Dim FirstName As String, LastName As String
    FirstName = "Patricia "
    LastName = "Katts"
    SheetName = GetFullName(FirstName, LastName)
End Sub

Private Function GetFullName$(First As String, Last As String)
    Dim FName As String
    Sheets.Add
    FName = First & Last
    ActiveSheet.Name = FName
    GetFullName = FName
End Function

您正在做的事情没有得到解释。