创build一个接受variables的过程,然后将另一个返回给Excel VBA中的调用过程

我想创build的function,将允许我将一个variables传递给一个过程,让它打开一个基于该variables的文件,然后将文件path返回到调用过程。 我有打开文件等的代码,但由于在程序中可以调用多个地方,我不希望它在那里,但只是将文件path返回到variables(然后可以使用从打开的文件加载字段)。

加载我正在使用的文件的代码如下,我将如何将其转换为一个过程来做我所需要的?

'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 

你是这个意思吗?

 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