OK. Learn basic testing.
There is one rule, and there are two ways (actually more, but I want to explain only two).
This is the rule:
Never presume that any of your code does what it is supposed to do until you have tested it.Applied to your code that means that you should test this line of your code:
myfolder = cboMonthNames.ValueDoes the variable MyFolder really contain the expected value?
Here are the two ways:-
- Use a MsgBox
The code is MsgBox MyFolder - Print to the Immediate Window
The code is Debug.Print MyFolder
You may have to make the Immediate Window visible in the VB Editor.
Actually, if the variable is empty the Immediate Window won't show anythign and you may wonder whether the Debug.Print command was really carried out. In that case, add a word to it, like,
Debug.Print "MyFolder = "; MyFolder. The semicolon indicates that the next item should also be printed. Use a comma if you would like to have a tab space before the next item.
So, this is what your code should look like:
- Code: Select all
Private Sub CommandButton2_Click()
Const FilePath = "C:\Users\ddempsey\Desktop\projects\dashboard project\MSO dashboard\New folder"
Dim MyFolder
Dim myfile
Dim strFileName As String
MyFolder = cboMonthNames.Value
Debug.Print MyFolder
' myfile = cboFileName.Value
' strFileName = Dir(FilePath & myfolder & myfile & ".xls")
' Workbooks.Open ("strFileName")
End Sub
Continue like that with MyFile and strFileName. Only after strFileName looks to you like it should be correct do you need to actually try to open the file.
Observe that I moved your declaration of the constant to the top of your code. It is good practice to separate declarations from the code. Some declarations
must be at the top of the module. Within a procedure the rules aren't as strict, but how can you see the code if it is cluttered up with declarations?
Please study this line of your code,
strFileName = Dir(FilePath & myfolder & myfile & ".xls"). Why is it different from the code I provided? And what effect does the difference have?
Actually,
FilePath & myfolder & myfile & ".xls" already is supposed to be the file name (except that you omitted both, the backslash at the end of the path constant AND the function I gave you that would make sure it is there). Using that file name in the Dir function would just return the same file name. However, if the file doesn't exist the Dir function will return nothing, "".
So, you arrive at different code for that part.
- Code: Select all
strFileName = FilePath & myfolder & myfile & ".xls"
If Len(Dir(strFileName)) Then
' proceed to open the file
End If
Of course, follow rule #1 laid out above. Test both, strFileName and Dir(strFileName) before you do anything with these constructs.
Have a great day!
Sisyphus
I do this for "honour and country" - much less of the latter, actually.
If I helped you, award points, plenty of them.
If I bored you, deduct points for being too long-winded. (I know, :lol)