PDA

View Full Version : User defined directory not working



willspill
12-17-2019, 07:55 AM
Hi (very new to VBA so please be patient with me),

I am trying to create a code which allows me to let the user define a file and then use the files directory in another macro. However, I receive the error message of 'Compile error: Variable not defined' using this code:

Sub ChooseDirectory()
Dim flder As FileDialog
Dim filename As String
Set flder = Application.FileDialog(msoFileDialogFilePicker)
With flder
.Title = "Select the file containing data"
.AllowMultiSelect = True
If .Show <> -1 Then GoTo NextCode
filename = .SelectedItems(1)
End With
NextCode:
GetFile = filename
Set flder = Nothing
End Sub

The error appears on the 'GetFile = filename' line highlighting 'GetFile'.

Thanks in advance for any help.

Paul_Hossler
12-17-2019, 09:18 AM
The message says that GetFile is not defined so just define it. Since you're not returning it from your sub, I assume you'll want to make it at least module level



Option Explicit


Dim GetFile As String ' <<<<<<<<<<<<<<<<<<<<<<<<


Sub ChooseDirectory()
Dim flder As FileDialog
Dim filename As String


Set flder = Application.FileDialog(msoFileDialogFilePicker)


With flder
.Title = "Select the file containing data"
.AllowMultiSelect = True
If .Show <> -1 Then GoTo NextCode
filename = .SelectedItems(1)
End With


NextCode:
GetFile = filename
Set flder = Nothing
End Sub