Extracting Filename from Dir()

送分小仙女□ 提交于 2020-01-17 03:27:08

问题


I have a macro that uses the Dir function.

MyFile = Dir(CurDir() & Sep & "*.xls")
Do While MyFile <> ""
     ...
     MyFile = Dir()
Loop

How do I extract just the filename from MyFile (exclude the extension)?


回答1:


It doesn't look like there is a convenient built-in function, so you'll have to do some string manipulation:

' Get just the file name and extension
lastPathIndex = InStrRev(MyFile, Application.PathSeparator)
If lastPathIndex >= 1 Then
    MyFile = Right(MyFile, Len(MyFile) - lastPathIndex)
End If

' Now get the file name without the extension  
lastDotIndex = InStrRev(MyFile, ".")
If lastDotIndex >= 1 Then
    MyFile = Left(MyFile, lastDotIndex - 1)
End If

' MyFile now contains just the filename



回答2:


The MyFile variable holds the file name with an extension and without the path.

Based on your input, you know the extension for any file found will be .xls , so you can use update your code with a single line

MyFile = Dir(CurDir() & Sep & "*.xls")
Do While MyFile <> ""
     MyFile = Left(MyFile, Len(MyFile) - 4)
     ...
     MyFile = Dir()
Loop



回答3:


Another method is

fileName = Split(MyFile, Sep)(UBound(Split(MyFile, Sep)))


来源:https://stackoverflow.com/questions/1452032/extracting-filename-from-dir

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!