在交替路径中搜索文件

时间:2016-11-10 19:55:28

标签: excel vba automation

我有一个VBA代码,可以找到并列出指定文件夹中的所有文件和文件夹。这是:

var totalPrice = function({price: price, taxRate: taxRate}){
    return price + price * taxRate;
};

* 1)如何获得当前月份? 2)如何获得当年? 3)如何以M-YY格式组合当前月/年并将其插入文件夹路径?

1 个答案:

答案 0 :(得分: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