制作全局文件路径

时间:2018-06-04 18:32:54

标签: excel vba error-handling global-variables filepath

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

这是提示用户选择文件的初始功能。该文件路径保存在变量" path"中。我将这个功能公之于众,意图使用" 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

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

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)

我的问题是它不允许我打开&#34;路径&#34;。

错误状态

  

&#34;运行时错误&#39; 1004&#39;:抱歉,我们无法找到。是不是有可能   移动,重命名或删除?&#34;

2 个答案:

答案 0 :(得分:1)

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

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

Sub Shipment_History()

    Dim path as string
    path = OpenFile1()

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

P.S。删除除Resume Leave语句之外的End Function之后的所有内容。

答案 1 :(得分: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