仅查找文件名而不是整个路径VBA Mac Office 2011

时间:2016-08-07 08:05:01

标签: vba filenames

所以我有一个宏运行,但它当前循环通过列A找到拉文件名路径(即Macintosh HD:Users:username:path:to:filename)。我希望它只找到文件名而不是完整路径。路径将不断变化,因此它必须只能提取文件名。我已经看过使用GetFileName,但是我使用的是Mac Office 2011,所以我遇到了让它运行的问题。有什么想法吗?

Sub CSVauto()
'
' CSVauto Macro
'
' Keyboard Shortcut: Option+Cmd+x
'
'   Declaring and setting variables for choosing CSV to import
    Dim csvFileName As Variant


''Prompt window to choose csv file
csvFileName = Application.GetOpenFilename(FileFilter:="")
If csvFileName = False Then Exit Sub
'Setting a variable to find Experimental form name in Data Summary
Dim whatToFind As String 'Declaring that variable
    If Right(csvFileName, 4) = ".csv" Then
        whatToFind = Replace(csvFileName, ".csv", "")
        MsgBox (whatToFind)
    End If
'Looping through A column to find csvFileName without .csv extension
Set cell = Range("A:A").Find(What:=whatToFind, LookIn:=xlValues, _
       LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
      MatchCase:=False)

If Not cell Is Nothing Then
      cell.Select
   End If

添加

Dim whatToFind As String 'Declaring that variable
Dim NoCsv As String
    If Right(csvFileName, 4) = ".csv" Then
        NoCsv = Replace(csvFileName, ".csv", "")
        whatToFind = Replace(NoCsv, ThisWorkbook.Path, "")‹

这给出了一个部分路径,而不是完整路径它是:FolderonDesktop:FolderofCSV:Filename

我认为它只会给我文件名,但至少我能够切掉它的一部分。现在我只需要摆脱两个层次,我会好的。

1 个答案:

答案 0 :(得分:1)

使用InStrRev查找文件路径中最后一次出现\的索引,并使用MidRight返回文件路径的文件名部分

enter image description here

Function getFileName(FilePath As String) As String

    getFileName = Mid(FilePath, InStrRev(FilePath, "\") + 1)

End Function

MAC

Function getFileName(FilePath As String) As String

    getFileName = Mid(FilePath, InStrRev(FilePath, "/") + 1)

End Function

enter image description here