Excel 在交替路径中搜索文件
我有一个VBA代码,可以查找并列出指定文件夹中的所有文件和文件夹。这是:Excel 在交替路径中搜索文件,excel,vba,automation,Excel,Vba,Automation,我有一个VBA代码,可以查找并列出指定文件夹中的所有文件和文件夹。这是: Sub Example1() Dim objFSO As Object Dim objFolder As Object Dim objFile As Object Dim i As Integer Set objFSO = CreateObject("Scripting.FileSystemObject") Set objFolder = objFSO.GetFolder("C:\Desktop\Test\2015\11-
Sub Example1()
Dim objFSO As Object
Dim objFolder As Object
Dim objFile As Object
Dim i As Integer
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFSO.GetFolder("C:\Desktop\Test\2015\11-16")
i = 1
For Each objFile In objFolder.Files
Cells(i + 1, 1) = objFile.Name
Cells(i + 1, 2) = objFile.Path
i = i + 1
Next objFile
End Sub
*
1) 如何获取当前月份?2) 如何获得本年度?3) 如何以这种格式M-YY组合当前月份/年份并将其插入文件夹路径 将文件的for循环放入另一个循环几个月
Imports System
Module module1
Sub Main()
Dim objFSO As Object
Dim objFolder As Object
Dim objFile As Object
Dim i As Integer
objFSO = CreateObject("Scripting.FileSystemObject")
For month As Integer = 11 to 12
Dim folderPath As String = "C:\Users\Admin\Desktop\Test\2015\" & month & "-16"
Console.WriteLine("Folder path = " & folderPath)
objFolder = objFSO.GetFolder(folderPath)
i = 1
For Each objFile In objFolder.Files
' Cells(i + 1, 1) = objFile.Name
Console.WriteLine("Cells(" & (i + 1) & ", 1) = " & objFile.Name)
' Cells(i + 1, 2) = objFile.Path
Console.WriteLine("Cells(" & (i + 1) & ", 2) = " & objFile.Path)
i = i + 1
Next objFile
Next month
End Sub
End Module
如果你也需要每年循环一次,你可以把上面的两个循环放在另一个循环里几年。以下代码从2016年到2099年有效
Sub Example1()
Dim objFSO As Object
Dim objFolder As Object
Dim objFile As Object
Dim i As Integer
Set objFSO = CreateObject("Scripting.FileSystemObject")
For year As Integer = 16 to 99
For month As Integer = 11 to 12
Dim folderPath As String = "C:\Desktop\Test\2015\" & month & "-" & year
Set objFolder = objFSO.GetFolder(folderPath)
i = 1
For Each objFile In objFolder.Files
Cells(i + 1, 1) = objFile.Name
Cells(i + 1, 2) = objFile.Path
i = i + 1
Next objFile
Next month
Next year
End Sub
因此,在这行中:folderPath=“C:\Desktop\Test\2015\”&month&“-16”..如果我希望它在当前日期之前的前一个月内每次都进行搜索,那么您需要减少它,而不是增加循环中的月份。只需将月份=11到12的
替换为月份=11到1的步骤-1
。这样的话,它将从11,10,9,8。。它为“for Month=11到12”行提供了一个错误,编译错误:参数不是可选的