通过excel中的列循环DateLastModified函数

时间:2013-11-22 05:17:55

标签: excel vba

我有一个包含数据的工作表,但我需要添加创建数据的时间。这个时间是我从中获取数据的文件的“上次修改时间”。

我已经在工作表的第一列中获得了“filename.txt”中的所有文件名,因此每行数据都可以引用到其文件中。我有这个函数从文件名中拉出LastModified-Date:

Function FileLastModified(strFullFileName As String)
strFullFileName = "C:\...\filefolder\" + Range("A1").Value
    Dim fs As Object, f As Object, s As String

    Set fs = CreateObject("Scripting.FileSystemObject")
    Set f = fs.GetFile(strFullFileName)

    s = UCase(strFullFileName) & vbCrLf
    s = f.DateLastModified
    FileLastModified = s

    Set fs = Nothing: Set f = Nothing


End Function

现在我希望该函数遍历A列中的所有文件名,并将所有LastModified-Times放在D列中。那么如何编辑

strFullFileName = "C:\.....\" + Range("A1").Value

自动从A-Column中提取文件名?

1 个答案:

答案 0 :(得分:0)

这样的东西?

Dim FSO As Object: Set FSO = CreateObject("Scripting.FileSystemObject")
Dim i As Long
Dim n As Long
Dim filenames As Variant
Dim lastModifiedTimes As Variant

'How many filenames are there? (should tailor this to your exact situation)
n = Range("A:A").Find("*", Range("A1"), SearchDirection:=xlPrevious).Row

filenames = Range("A1").Resize(n, 1).Value 'load all fnames from sheet to array

ReDim lastModifiedTimes(1 To n, 1 To 1)
For i = 1 To n
    lastModifiedTimes(i,1) = _
        FSO.GetFile("C:\.....\" & filenames(i,1)).DateLastModified
Next i

'Slap times array onto sheet
Range("D1").Resize(n, 1).Value = lastModifiedTimes

请注意,我删除了FileLastModified包装函数,因为它实际上只包装了一个东西,它可以被一行代码替换掉。