File vba搜索文件夹并按名称选择文件

File vba搜索文件夹并按名称选择文件,file,vba,selection,File,Vba,Selection,我在文件夹中有很多文件,它们的结构名称如下: "prof102122013@10.18.41.csv" 其中,“02122013”位为日期-2013年12月2日。其中一些是在同一天制作的。我想创建一个文件,将当天制作的所有工作簿放在一个大文件中。到目前为止,我正在努力获得打开一个特定日期文件的选择性。有人知道什么样的代码可以帮我解决这个问题吗 编辑:解决了,谢谢大家的帮助!以下是对我有效的代码: folder_location = Application.ActiveWorkbook.Path

我在文件夹中有很多文件,它们的结构名称如下:

"prof102122013@10.18.41.csv"

其中,“02122013”位为日期-2013年12月2日。其中一些是在同一天制作的。我想创建一个文件,将当天制作的所有工作簿放在一个大文件中。到目前为止,我正在努力获得打开一个特定日期文件的选择性。有人知道什么样的代码可以帮我解决这个问题吗

编辑:解决了,谢谢大家的帮助!以下是对我有效的代码:

 folder_location = Application.ActiveWorkbook.Path

i2 = 0

strFile = Dir(folder_location & "\")

'looping through to find the right file names and putting them all in an array
While strFile <> ""
    If Right(strFile, 3) = "csv" Then
                file_to_analyse = Split(strFile, "@")
                If Right(file_to_analyse(0), 8) = date_we_want_to_analyse_on Then
                    found_files_to_analyse(i2) = strFile
                    i2 = i2 + 1
                End If
            End If
    strFile = Dir
Wend
folder\u location=Application.ActiveWorkbook.Path
i2=0
strFile=Dir(文件夹位置&“\”)
'循环查找正确的文件名并将它们全部放入一个数组中
而strFile“”
如果正确(strFile,3)=“csv”,则
文件\u to \u analysis=Split(strFile,“@”)
如果正确(文件要分析(0),8)=我们希望分析的日期
找到要分析的文件(i2)=标准文件
i2=i2+1
如果结束
如果结束
strFile=Dir
温德

是否要根据文件保存日期或文件名合并文件。名为“昨天日期”的文件可以在今天保存,并带有今天的日期。我猜您必须解析文件名,并在do-while循环中应用日期(文件名中)前后的逻辑,直到目录中的所有文件都搜索到该条件。如果满足条件,则将打开的文件复制到文件中的工作表中。如果不满足该条件,则跳过该文件。下面可能会有所帮助

For each date which needs to be consolidated, do the following in a loop or an in a user prompted message box where the user inputs the date. You also need to chose whether you want the consolidation to happen in the workbook from where you are launching the macro or a separately opened workbook. The code below assumes you are consolidating in the same workbook.

Path = Path of the directory in which the files are stored

Flname = Dir(Path & "*.csv")

Do While Flname <> "" 

If ' file check Condition' Then
    Filecheckname = True  ' Checks if file follows the naming conventions desired
Else
    Filecheckname = False
End If

If Filecheckname Then
    FlDate = getDate(Flname)     ' extracts the date from the file name
Else
    GoTo Errorhandler ' If there is an error, then the macro stops with a message to the user
End If

If FlDate<> Date Then

    flsskpd = flsskpd + 1       ' If the date criteria is not met, the file is skipped with an increment to the fileskipped counter
    Flname = Dir()
Else

     Workbooks.Open Filename:=Path & Flname, ReadOnly:=True

'Code to Copy into consolidated workbook (ThisWorkbook)
filesmoved = filesmoved + 1
     Flname = Dir()
End if

Loop

Message to user about how many files skipped and consolidated. 

Prompt user whether to continue to the next date consolidation, if yes, continue or take the new date as an input and repeat the loop
对于每个需要合并的日期,在用户输入日期的循环或用户提示消息框中执行以下操作。您还需要选择是在启动宏的工作簿中进行合并,还是在单独打开的工作簿中进行合并。下面的代码假定您正在同一工作簿中合并。
Path=存储文件的目录的路径
Flname=Dir(路径和“*.csv”)
当名称为“”时执行此操作
如果是“文件检查条件”,则
Filecheckname=True'检查文件是否遵循所需的命名约定
其他的
Filecheckname=False
如果结束
如果是Filecheckname,则
FlDate=getDate(Flname)'从文件名中提取日期
其他的
GoTo Errorhandler'如果出现错误,则宏将停止并向用户发送消息
如果结束
如果是日期,那么
flsskpd=flsskpd+1'如果不满足日期条件,则跳过该文件,并向FILESKIPED计数器增加一个增量
Flname=Dir()
其他的
工作簿。打开文件名:=路径和名称,只读:=真
'要复制到合并工作簿(此工作簿)中的代码
filesmoved=filesmoved+1
Flname=Dir()
如果结束
环
向用户发送的有关跳过和合并了多少文件的消息。
提示用户是否继续到下一个日期合并,如果是,则继续或将新日期作为输入并重复循环
如果您希望VBA“搜索”目录中的文件/文件夹,我认为您需要使用类似以下内容:

Option Explicit
Option Compare Text
Public Enum xlSearchMode
    xlFilesOnly = 0
    xlFoldersOnly = 1
    xlFilesAndFolders = 2
End Enum
Function SearchInDirectory(FName As String, Optional FoName As String, Optional SearchMode As xlSearchMode = xlFilesOnly, Optional ExactMatch As Boolean = True) As Variant
    'By Abdallah Khaled Ali El-Yaddak
    'Returns an array of strings with files/folders matching what you are searching for.
    'If nothing is found, it returns an array of one empty string element.
    '-------------'
    'FName (String): The file/folder to look for
    '[FoName] (String): The directory to search in, if omitted, CurDir will be used.
    '[SreachMode] (xlSearchMode): xlFilesOnly (default) = Look for files only | xlFoldersOnly = Look for folders only | xlFilesAndFolders = Look for both
    '[Exactmatch] (Boolean): True (default) = Look only for this string (case insenstive) | False = Sreach for any files/folders that includes this string in their name
    Dim FSO As Object, File As Object, Folder As Object, Fnames() As String, i As Long, SubNames As Variant, SubFolder As Object
    If FoName = "" Then FoName = CurDir
    If Right(FoName, 1) <> "\" Then FoName = FoName & "\"
    ReDim Fnames(1 To 1) As String
    Set FSO = CreateObject("Scripting.FileSystemObject")
    Set Folder = FSO.GetFolder(FoName)
    If SearchMode = xlFilesOnly Or SearchMode = xlFilesAndFolders Then
        For Each File In FSO.GetFolder(Folder).Files
            If (ExactMatch And SubFolder.Name = FName) Or _
                    (Not ExactMatch And SubFolder.Name Like "*" & FName & "*") Then
                Fnames(UBound(Fnames)) = File.Path
                ReDim Preserve Fnames(1 To UBound(Fnames) + 1)
            End If
        Next
    End If
    If SearchMode = xlFoldersOnly Or SearchMode = xlFilesAndFolders Then
        For Each SubFolder In FSO.GetFolder(Folder).subFolders
            If (ExactMatch And SubFolder.Name = FName) Or _
                    (Not ExactMatch And SubFolder.Name Like "*" & FName & "*") Then
                Fnames(UBound(Fnames)) = SubFolder.Path
                ReDim Preserve Fnames(1 To UBound(Fnames) + 1)
            End If
        Next
    End If
    For Each SubFolder In FSO.GetFolder(Folder).subFolders
        SubNames = SearchInDirectory(FName, SubFolder.Path, SearchMode, ExactMatch)
        If SubNames(LBound(SubNames)) <> "" Then
            For i = LBound(SubNames) To UBound(SubNames)
                Fnames(UBound(Fnames)) = SubNames(i)
                ReDim Preserve Fnames(1 To UBound(Fnames) + 1)
            Next
        End If
    Next
    If UBound(Fnames) > 1 Then ReDim Preserve Fnames(1 To UBound(Fnames) - 1)
    SearchInDirectory = Fnames
End Function
Sub Test()
    Dim a As Variant, i As Long
    a = SearchInDirectory(date_we_want_to_analyse_on, folder_location, xlFilesOnly, Flase)
    For i = LBound(a) To UBound(a)
        Debug.Print a(i)
    Next
End Sub
注意事项:

  • 此解决方案不适用于MAC(仅在windows上测试)
  • 搜索较大的目录(其中的文件/文件夹数)将花费更长的时间

  • 尝试
    FileSystemObject
    读取和写入文件。您也可以使用
    FSO
    搜索文件和文件夹。你试过什么了吗?你能提供一个示例文件名列表吗?我认为您可以使用@PankajJaju所说的
    FileSystemObject
    获取所需内容,并将其与
    RegExp
    库相结合,以查找每个文件名的日期(您将在问题下方找到一个“编辑”链接,允许您添加示例)。干杯!我使用了
    Application.ActiveWorkbook.Path
    来查找文件夹,然后是Peekay下面答案的一个变体,使用:
    While strFile''如果正确(strFile,3)=“csv”,然后file to_analysis=Split(strFile,“@”)如果正确(file to_analysis(0),8)=日期我们想分析,然后找到文件to_analysis(i2)=strFile i2=i2+1 End If End If strFile=Dir Wend
    感谢您的帮助,我非常感谢!(编辑:我将在我的问题部分“因为我无法在这些评论中将其格式化为好看的块”中编写代码)