2016-11-10 67 views
-1

我有一个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-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格式的当前月份/年份合并到文件夹路径中?

+0

VB.NET IsNot运算VBA – Plutonix

回答

0

将文件的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 
+0

因此,在这一行:FOLDERPATH = “C:\桌面\测试\ 2015年\” &月& “-16” .... ..&month&....表示它选择当前月份? – Mashkaramashka

+0

是的,这就是代码中的内容。 – NavkarJ

+0

我已经添加了多年,假设不同年份的文件夹位于2015文件夹内(可以更改) – NavkarJ