Lev
Lev

Reputation: 113

Can't use dir function with string variable and (*) sign

I am trying to use the dir function with (*) sign in order to auto-complete a partial pathname (In this example: Deskt -> Desktop) This is the code I tried, but it says I got a syntax error:

Sub check()
    Dim folderpath As String
    folderpath = "C:\Users\levs\Deskt"
    MsgBox (Dir(folderpath*, vbDirectory))
End Sub

However, if I write the code without using the variable, it will work:

MsgBox (Dir("C:\Users\levs\Deskt*", vbdirectory)

So is it possible to use a variable with this function?

Thanks alot!

Upvotes: 1

Views: 466

Answers (3)

CodeIsLife
CodeIsLife

Reputation: 1245

your need to concatenate widlcard and your folder path

sub check()
    Dim folderpath As String
    folderpath = "C:\Users\levs\Deskt"
    MsgBox (Dir(folderpath & "*", vbDirectory))
End Sub

Upvotes: 0

This is more a syntax than another thing...

if you do folderpath = "myPath" then the variable folderpath is a String, now if you do something like folderpath*, then you are using an unary operator to a variable that holds a string...

Take in consideration that this is totally different operation to concatenating the string with "*"...() in some languages can be a multiply operator, but in others something more complex like a pointer...

Solution:

Do the concatenation properly, i.e replace MsgBox (Dir(folderpath*, vbDirectory)) for

MsgBox (Dir(folderpath&"*", vbDirectory))

or event better do the concatenation in the declaration...

your final method should look like:

Sub check()
Dim folderpath As String
   folderpath = "C:\Users\levs\Deskt*"
   MsgBox (Dir(folderpath, vbDirectory))
End Sub

Upvotes: 0

Malk
Malk

Reputation: 11983

You need to further build up the string:

MsgBox (Dir(folderpath & "*", vbDirectory))

Upvotes: 1

Related Questions