Consulting

Results 1 to 3 of 3

Thread: Sub Returning Workbook

  1. #1
    VBAX Regular
    Joined
    Jun 2010
    Posts
    8
    Location

    Sub Returning Workbook

    Hello. I'm trying to use a sub to open up a workbook. The code I'm working on is:

    [VBA]Dim wb As Workbook
    Set wb = WorkbookOpen("C:\File.xls")

    Private Function WorkbookOpen(Path As Variant) As Workbook

    On Error GoTo EndofSub

    Dim wb As Workbook
    Set wb = Workbooks.Open(Path, True, True)
    WorkbookOpen = wb

    EndofSub:


    End Function[/VBA]

    The reason I open the workbook inside a sub is to isolate an error that occurs if the selected file is already open. If you click "No" to re-opening the file, the Open method fails and raises an error.

    I'm not sure why the code above doesn't work. It either does not return a workbook object, or it does not set the variable wb as that workbook.

    Any help would be appreciated. Thanks!

  2. #2
    Distinguished Lord of VBAX VBAX Grand Master Bob Phillips's Avatar
    Joined
    Apr 2005
    Posts
    25,453
    Location
    [vba]
    Dim wb As Workbook
    Set wb = WorkbookOpen("C:\File.xls")

    Private Function WorkbookOpen(Path As String) As Workbook

    On Error Goto EndofSub

    Dim wb As Workbook
    Set wb = Workbooks.Open(Path, True, True)
    Set WorkbookOpen = wb

    EndofSub:


    End Function
    [/vba]
    ____________________________________________
    Nihil simul inventum est et perfectum

    Abusus non tollit usum

    Last night I dreamed of a small consolation enjoyed only by the blind: Nobody knows the trouble I've not seen!
    James Thurber

  3. #3
    Administrator
    VP-Knowledge Base
    VBAX Grand Master mdmackillop's Avatar
    Joined
    May 2004
    Location
    Scotland
    Posts
    14,489
    Location
    [VBA]
    Sub Test()
    Dim wb As Workbook
    Dim Path As String
    Dim WBook As String
    WBook = "File.xls"
    Path = "C:\"
    On Error Resume Next
    Set wb = Workbooks(WBook)
    On Error GoTo 0
    If wb Is Nothing Then Set wb = Workbooks.Open(Path & WBook)
    End Sub

    [/VBA]
    MVP (Excel 2008-2010)

    Post a workbook with sample data and layout if you want a quicker solution.


    To help indent your macros try Smart Indent

    Please remember to mark threads 'Solved'

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •