制作全局文件路径

问题描述 投票:1回答:2

目标:使用开放功能允许用户在他们选择在多个功能中打开的任何文件上运行命令(路径在公共功能中)。

这是提示用户选择文件的初始功能。该文件路径保存在变量“path”中。我将这个功能公之于众,意图在多个领域使用“路径”(全球化)。

Public Function OpenFile1() As String
    On Error GoTo Trap

    Dim fd As FileDialog
    Set fd = Application.FileDialog(msoFileDialogFilePicker)

    With fd
        .Title = "Open Sterling Shipment History" 'Name for file
        .Filters.Clear
        .ButtonName = " Open "
        .AllowMultiSelect = False
    End With

    If fd.Show <> 0 Then OpenFile1 = fd.SelectedItems(1)

Leave:
    Set fd = Nothing
    On Error GoTo 0
Exit Function

Trap:
    MsgBox Err.Description, vbCritical
    Resume Leave
    Dim path As String
path = OpenFile1() 'Calls in file

If path <> vbNullString Then Debug.Print path
Workbooks.Open (path)


'rename the path variable for each function
'so that I can call in different files with that name
End Function

这是第二个函数的摘录,它尝试从变量“path”调用文件路径,使用它来打开工作簿并更改工作簿。

Sub Shipment_History()
Call OpenFile1
Dim sshist As Workbook
Set sshist = Workbooks.Open(path)
Columns("E:E").Select
Selection.Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove

我也尝试过:

  Sub Shipment_History()
  Call OpenFile1
  Workbooks.Open(path)

我的问题是它不允许我打开“路径”。

错误说明

“运行时错误'1004':抱歉,我们找不到。它是否可能被移动,重命名或删除?”

excel vba error-handling global-variables filepath
2个回答
1
投票

由于函数返回一个字符串(路径)并且它是公开可用的,因此您不需要公共变量来存储路径。

在本地声明路径变量并将其值设置为从函数返回的值(路径):

Sub Shipment_History()

    Dim path as string
    path = OpenFile1()

    If path <> vbNullString Then Workbooks.Open(path)
End Sub

附:除了Resume Leave声明之外,删除End Function之后的所有内容。


0
投票

path必须在任何Function或Subscript之外声明为public String,该函数不需要是public,它是变量。

在模块上试试这个:

Public path As String

Function setPathValue(ByVal dataPassed As String)
    path = dataPassed
End Function

Sub givePathVal()
    setPathValue ("This is path value")
End Sub

Sub showPathVal()
    MsgBox path
End Sub
© www.soinside.com 2019 - 2024. All rights reserved.