设置VBA功能的返回值时出错

时间:2011-10-06 14:10:14

标签: excel vba

我正在简要介绍VBA以自动化一些Excel工作流程。我有一个创建工作表并返回它的函数。我把它称之为:

Dim ws As Worksheet
Dim wb As Workbook

Set wb = Application.ActiveWorkbook
Set ws = makeNewWorksheet(wb)

功能是:

Function makeNewWorksheet(wb) As Worksheet
    Dim wsName As String
    Dim ws As Worksheet
    Dim newWs As Worksheet

    wsName = "Bounced " & Format(Now, "dd-mm-yyyy")
    For Each ws In wb.Worksheets
        If ws.Name = wsName Then
            Set newWs = ws
            Exit For
        End If
    Next
    If newWs Is Nothing Then
        Set ws = wb.Sheets.Add
        With ws
            .Name = wsName
            .Move after:=Sheets(Sheets.Count)
        End With
    End If
    makeNewWorksheet = ws
End Function

当我尝试在最后一行(makeNewWorksheet = ws)上分配函数的返回值时,出现错误:

Object variable or With block variable not set

我找不到任何在线文档似乎都适用于这种情况。一切都已定义,ws变量具有值。

编辑:Re。接受的答案如下。 Here's set关键字的解释。

1 个答案:

答案 0 :(得分:3)

此:

makeNewWorksheet = ws

应该是:

set makeNewWorksheet = ws