Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Renaming Files 1

Status
Not open for further replies.

SeaRay

Technical User
Jan 8, 2002
20
0
0
US
Is there a way to refer to a file that changes names each day. I have a PC based cash register that I import files from every day. One day the file is named "CRDAY_25.001" and the next day it is named "CRDAY_26.001". The name before the underscore is always the same and the .001 extenstion is always the same. The number in the middle goes up by one each day. Can I rename the file using a "like" function to refer to the "changing file"?
E.g. Private Sub Command1_Click()
Name "C:\~Master Files\SSM\001\Crday_*.001" As "C:\~Master Files\SSM\001\Credit.txt"
End Sub
(With the * being the wild card)
Thanks, Rick
 
You can't do it quite like that, but with a little more code you can get the job done.

First, though, think carefully about what you're asking for. Are you absolutely sure there will never be more than one file with a name like "Crday_*.001"? If somehow there happened to be 2 or more such files, you could wind up trying to name both of them to the same name, which would cause a runtime error. Or, you might rename only one of them, and which was it was can be unpredictable. Your processing flow may not ever result in this situation, but can you be sure some well-meaning user won't copy an extra "Crday_23.001" file to this folder while trying to solve a problem?

If you're quite sure you don't need to worry about multiple matching files, then the following short code excerpt will work for you:
Code:
    Dim strFileName As String
    strFileName = Dir$("C:\~Master Files\SSM\001\Crday_*.001")
    If strFileName <> &quot;&quot; Then
        Name strFileName As &quot;Credit.txt&quot;
    End If

What this does is use the Dir$() function to find the first matching file name, putting that name in strFileName. Dir$() allows you to use the &quot;*&quot; (and &quot;?&quot;) wildcard characters, which is similar to what you were looking for with the 'like' idea. Once you have the file name in a variable, you can use that variable instead of the string literal in the Name statement.

Potential shortcomings with this approach are:
1. If there really are multiple matching file names in the folder for some reason, this code will rename only one of them, ignoring the others. Which one it happens to see first is unpredictable.
2. If for some reason there are no matching file names, this code won't do anything at all. That could leave you wondering what happened later on, when your logic tries to do something with the Credit.txt file. Rick Sprague
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top