从文件路径excel vba中提取所需的文件夹

时间:2014-06-04 10:20:16

标签: excel vba excel-vba

我有一个文件路径(实际上是工作表的连接路径),格式如下:

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

我只想从上面的文件路径中提取 20140522 。 我尝试在这里使用类似问题的回答[1]:How to extract groups of numbers from a string in vba,但它们似乎不适用于我的情况。

任何人都能帮助我吗?

5 个答案:

答案 0 :(得分:0)

请在下面找到

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

答案 1 :(得分:0)

以下答案从范围获取文件路径,而不是固定字符串。如果你计划从你的工作表中获取你的文件名,那就更方便了。我想你是。

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

答案 2 :(得分:0)

尝试以下方法。选择了文件夹。

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

End Sub

答案 3 :(得分:0)

我通过搜索解决方案来找到您的问题,该解决方案是如何从此文件夹路径中的文件获取文件夹路径。但是您的问题与我的需求不完全匹配。对于那些通过您的问题标题找到它的目的与我发现的目的相同的人,以下是我的功能:

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对象,我认为不值得创建它。

答案 4 :(得分:0)

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

Dim fileName As String

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

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