繁体   English   中英

从文件路径中提取文件夹名称

[英]Extract a folder name from file path

我有以下格式的文件路径(它是工作表的连接路径):

C:\\ExcelFiles\\Data\\20140522\\File1_20140522.csv

我想提取20140522

我尝试使用如何从 vba 中的字符串中提取数字组的响应,但在我的情况下它们似乎不起作用。

如下请见

Filename = "C:\ExcelFiles\Data\20140522\File1_20140522.csv"
a = Replace(Mid(Filename, InStrRev(Filename, "_") + 1, Len(Filename)), ".csv", "")

请尝试以下操作。 文件夹被选中。

Sub Folder_S()
Dim sFolder As FileDialog
On Error Resume Next
Set sFolder = Application.FileDialog(msoFileDialogFolderPicker)
If sFolder.Show = -1 Then
    Folder_Select sFolder.SelectedItems(1), True
End If
End Sub
Sub Folder_Select(ByVal SourceFolderName As String, ByVal IncludeSubfolders As Boolean)
Dim FSO As Object
Dim SourceFolder As Object
Dim FileItem As Object
Dim strFile As String
Dim FileName As Variant
Dim pathParts() As String
Dim pathPart As String
Dim i As Long
Set FSO = CreateObject("Scripting.FileSystemObject")
Set SourceFolder = FSO.GetFolder(SourceFolderName)
pathParts = Split(SourceFolder.Path, Application.PathSeparator)
pathPart = SourceFolder.Path
For i = 0 To UBound(pathParts)
    If pathParts(i) = "20140522" Then
        pathPart = pathParts(i - 0)
        Exit For
    End If
Next i
Row = ActiveCell.Row
With CreateObject("Scripting.Dictionary")
    For Each FileItem In SourceFolder.Files
        strFile = FileItem.Name
        .Item(strFile) = Array(FileItem.Name)
    Next FileItem
    If .Count > 0 Then
        For Each FileName In .Items
            Cells(Row, 2).Formula = pathPart
        Next FileName
    End If
End With

结束子

我通过搜索解决方案如何从位于此文件夹路径内的文件中获取文件夹路径来发现您的问题。 但是你的问题并不完全符合我的需要。 对于那些根据您的问题标题会发现它的目的与我发现的相同的人,以下是我的功能:

Function getFolderPathFromFilePath(filePath As String) As String

    Dim lastPathSeparatorPosition As Long

    lastPathSeparatorPosition = InStrRev(filePath, Application.PathSeparator)

    getFolderPathFromFilePath = Left(filePath, lastPathSeparatorPosition - 1)

End Function

在为此目的的一些解决方案中,我使用了FSO,但它需要资源,如果您只需要这个简单的功能,我认为创建FSO对象不值得。

接受的答案不准确读取文件夹名称。 这是更多动态代码。 使用 splitter 根据分隔符拆分字符串并创建一个数组。 现在读取数组中的倒数第二个元素,即文件夹名称。

Dim fileName As String

fileName = "C:\ExcelFiles\Data\20140522\File1_20140522.csv"

Dim vPathSplitter As Variant
vPathSplitter = Split(fileName, "\")
MsgBox (vPathSplitter(UBound(vPathSplitter) - 1))

以下答案从一个范围而不是固定字符串中获取您的文件路径。 如果您打算从工作表中获取文件名,那就更方便了,我想您是这样。

Sub GetFileDate()

Dim filename As String

filename = Sheets("Sheet1").Range("C9").Value 'Or Wherever your file path is

MsgBox Replace(Right(filename, 12), ".csv", "")


End Sub

这假设您提取的数字始终是 YYYYMMDD 格式的日期,并且文件类型始终为 .csv

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM