0

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

加载我正在使用的文件的代码如下,我将如何将其转换为程序来执行我需要的操作?:

        '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
4

1 回答 1

2

你的意思是这样吗?

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
于 2013-02-01T09:04:45.593 回答