你如何获得文件名而不是打开文件的整个文件路径?

时间:2012-01-31 20:18:08

标签: excel vba filenames getopenfilename

换句话说,我需要在调用Application.GetOpenFileName()方法后进行一些字符串处理吗?

5 个答案:

答案 0 :(得分:10)

为什么要重新发明轮子并写出大量的样板代码?只需使用已编写并经过测试和调试的现有FileSystemObject的GetFileName方法:

filename = FSO.GetFileName(path)

这是一个有效的例子:

Dim path As String
Dim filename As String
Dim FSO As Scripting.FileSystemObject
Set FSO = New FileSystemObject

path = "C:\mydir\myotherdir\myfile.txt"

filename = FSO.GetFileName(path) 'Bingo. Done.

Debug.Print filename ' returns "myfile.txt"

' Other features:
Debug.Print FSO.GetBaseName(path) ' myfile
Debug.Print FSO.GetExtensionName(path) ' txt
Debug.Print FSO.GetParentFolderName(path) ' C:\mydir\myotherdir
Debug.Print FSO.GetDriveName(path) ' C:
' et cetera, et cetera.

您需要按如下方式设置参考: 工具>参考文献...>设置Microsoft Scripting Runtime旁边的复选标记。

否则使用后期绑定:

Dim FSO As Object
Set FSO = CreateObject("Scripting.FileSystemObject")

答案 1 :(得分:5)

我正在使用这些函数进行文件名处理。最后一个是你需要的那个。

Public Function FilePathOf(ByVal s As String) As String
    Dim pos As Integer

    pos = InStrRev(s, "\")
    If pos = 0 Then
        FilePathOf = ""
    Else
        FilePathOf = Left$(s, pos)
    End If
End Function

Public Function FileNameOf(ByVal s As String) As String
    Dim pos1 As Integer, pos2 As Integer

    pos1 = InStrRev(s, "\") + 1
    pos2 = InStrRev(s, ".")
    If pos2 = Len(s) Then pos2 = pos2 + 1
    If pos2 = 0 Then pos2 = Len(s) + 1
    FileNameOf = Mid$(s, pos1, pos2 - pos1)
End Function

Public Function FileExtOf(ByVal s As String) As String
    Dim pos As Integer

    pos = InStrRev(s, ".")
    If pos = 0 Then
        FileExtOf = ""
    Else
        FileExtOf = Mid$(s, pos + 1)
    End If
End Function

Public Function FileNameExtOf(ByVal s As String) As String
    FileNameExtOf = Mid$(s, InStrRev(s, "\") + 1)
End Function

答案 2 :(得分:1)

激活有问题的文件:

Function getname()

arr = Split(ActiveDocument.FullName, "\")
Debug.Print arr(UBound(arr))

End Function

我假设您正在使用Word,因此使用“ActiveDocument”。在适当的情况下将其更改为“ActiveWorksheet”等

答案 3 :(得分:0)

'越简单总是更好!! (替换适用的单元位置R1C1,以及路径的字符串长度)

Dim TheFile As String  
Dim TheFileLessPath As String  

Function getname()  
Workbooks.Open filename:=TheFile  
TheFileLessPath = Mid(TheFile, 12, 7)

ActiveCell.FormulaR1C1 = TheFileLessPath
End Function

答案 4 :(得分:0)

在这种情况下,您正在使用Application.GetOpenFilename(),因此您确定该文件实际存在于磁盘上,因此最简单的方法是使用Dir()。

fileName = Dir(filePath)

完整代码是:

Dim fileName, filePath As Variant

filePath = Application.GetOpenFilename("Excel files (*.xlsm), *.xlsm", , "Select desired file", , False)

If filePath = False Then
    MsgBox "No file selected.", vbExclamation, "Sorry!"
    Exit Sub
Else

    'Remove path from full filename
    fileName = Dir(filePath)

    'Print file name (with extension)
    MsgBox "File selected." & vbCr & vbCr & fileName, vbInformation, "Sucess!"

End If