2

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

4

5 回答 5

15

为什么要重新发明轮子并编写大量样板代码?只需使用已经为您编写、测试和调试过的现有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")
于 2012-02-01T07:57:16.173 回答
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
于 2012-01-31T20:22:48.893 回答
1

然后激活相关文件:

Function getname()

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

End Function

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

于 2012-02-05T00:52:44.220 回答
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
于 2014-05-01T00:02:36.683 回答
0

In this case, you are using Application.GetOpenFilename(), so you are sure that file physically exists on disk, so the simplest approach will be to use Dir().

fileName = Dir(filePath)

Full code is:

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
于 2017-03-23T06:04:28.817 回答