开发者

Error setting return value of a VBA function

I'm having a brief foray in to VBA to automate some Excel workflow. I've got a function that creates a worksheet and returns it. I call it as follows:

Dim ws As Worksheet
Dim wb As Workbook

Set wb = Application.ActiveWork开发者_Go百科book
Set ws = makeNewWorksheet(wb)

The function is:

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

When I try to assign the return value of the function on the last line (makeNewWorksheet = ws), I get an error:

Object variable or With block variable not set

None of the online docs I can find seem to apply in this situation. Everything is defined and the ws variable has a value.

Edit: Re. the accepted answer below. Here's an explanation of the set keyword.


This:

makeNewWorksheet = ws

should be:

set makeNewWorksheet = ws
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜