Goal: Make a public constant to use as workbook within multiple functions. The constant is obtained by prompting the user to open a specific file. (This is done because the file is updated monthly and each month has a designated name) How can I reference the open workbook without opening it multiple times?
Details: I have tried to avoid opening multiple times by deleting the "path = OpenFile()". I also tried to make the functions public, the variables are still contained within their original function. I'm not able to use the defined variables across functions. The error states either:
"Subscript out of Range"
or
"Object Required"
EDIT The error refers to
mvmtqt.Activate
and any additional references to variables stated in a previous function but not restated in the newer function. There are several functions not included to spare space for the question.
The additional openfile1() and openfile2() and so forth refer to copies of openfilee().
Code:
Public Function OpenFilee() 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
.InitialFileName = "Dialog start-up path"
.Filters.Clear
' .Filters.Add "Text Documents (*.txt)", "*.txt", 1
.ButtonName = " Open "
.AllowMultiSelect = False
End With
If fd.Show <> 0 Then OpenFilee = fd.SelectedItems(1)
Leave:
Set fd = Nothing
On Error GoTo 0
Exit Function
Trap:
MsgBox Err.Description, vbCritical
Resume Leave
End Function
Public Function ShipmentHistPt2()
Dim path1 As String
path1 = OpenFile1()
If path1 <> vbNullString Then Workbooks.Open (path1)
Dim mvmtln As Workbook
Set mvmtln = Workbooks.Open(path1)
Dim path2 As String
path2 = OpenFile2()
If path2 <> vbNullString Then Workbooks.Open (path2)
Dim mvmtqt As Workbook
Set mvmtqt = Workbooks.Open(path2)
mvmtqt.Activate
Sheets("Sheet1").Select
Issue: Whenever I try to activate the window(mvmtqt.Activate) it initiates opening the file again(if I define the variable within the function again), which not only slows down the process, but it also eliminates all previous changes.