Search code examples
excelvbaprocedureoutput-parameter

Creating a procedure that takes in a variable then returns another to the calling procedure in Excel VBA


I want to create functionality that will allow me to pass a variable to a procedure, have it open a file based on that variable, and then return the filepath into calling procedure. I have the code for opening the file etc, but as there are multiple places in the procedure where it could be called, I don't want it to be there, but just to return the filepath into a variable (which can then be used to load fields from the opened file).

The code to load the file that I am using is below, how would I convert this to a procedure to do what I need?:

        'Open the file
        NameOfFile = ActiveWorkbook.Worksheets("Parameters").Cells(8, 2).Value
        PathToFile = Left$(NameOfFile, InStrRev(NameOfFile, "\") - 1)
        FileNameNoPath = Mid$(NameOfFile, InStrRev(NameOfFile, "\") + 1)
        NameOfFile = FileNameNoPath
        CompleteFilePath = PathToFile & "\" & NameOfFile

        On Error Resume Next
        Set File1 = Workbooks(NameOfFile)

        If Err.Number <> 0 Then
        'Open the workbook
          Err.Clear
          Set File1 = Workbooks.Open(CompleteFilePath, UpdateLinks:=False)
          CloseIt = True
        End If

        'Check and make sure workbook was opened
        If Err.Number = 1004 Then
            MsgBox "File is missing, please check your path!" _
            & vbNewLine & NameOfFile
            Exit Sub
        End If
        On Error GoTo 0

Solution

  • You mean like this?

    Option Explicit
    
    Dim FilePath As String
    
    Sub Sample()
        Dim FileToOpen As String
    
        FileToOpen = "C:\Temp\Sample.xlsx"
    
        OpenFile FileToOpen
    
        Debug.Print FilePath
    End Sub
    
    Sub OpenFile(strFile As String)
        FilePath = Left$(strFile, InStrRev(strFile, "\") - 1)
    
        '
        '~~> Rest of the code
        '
    End Sub