VBA从FTP服务器创建文件列表

时间:2016-07-15 02:31:13

标签: excel-vba ftp vba excel

寻找VBA代码以在FTP服务器上创建文件列表。理想情况下,包含文件属性(例如创建日期/时间文件)会很棒。

1 个答案:

答案 0 :(得分:4)

我创建了一个名为FileInformation的类和一个函数getFileList,它将返回一个FileInformation数组。 GetFTPFileList允许您将getFileList与ftp服务器一起使用。

enter image description here

类文件信息


    Option Explicit

    Public FilePath
    Public FolderPath
    Public FileExtension

    Public Sub setValues(localRoot, fso, f)
        FilePath = f.Path
        FolderPath = f.ParentFolder.Path
        FileExtension = fso.GetExtensionName(FilePath)
    End Sub

其余代码进入普通代码模块。

    Sub PrintFileInformation()
        Const Username As String = ""
        Const Password As String = ""
        Const ftpSite As String = ""
        Const ftpRoot As String = ""
        Dim arFiles
        Dim i As Long

        arFiles = getFTPFileList(Username, Password, ftpSite, ftpRoot)

        For i = 0 To UBound(arFiles)
            Debug.Print arFiles(i).FilePath
            Debug.Print arFiles(i).FolderPath
            Debug.Print arFiles(i).FileExtension
        Next

    End Sub

    Function getFTPFileList(Username As String, Password As String, ftpSite As String, ftpRoot As String)

        ftpRoot = "ftp://" & Username & ":" & Password & "@" & ftpSite & "/" & ftpRoot
        getFTPFileList = getFileList(ftpRoot)

    End Function

    Function getFileList(localRoot As String, Optional fld, Optional ftpArray)
        Dim fso, f, baseFolder, subFolder, ftpFile, i

        Set fso = CreateObject("Scripting.Filesystemobject")

        If IsMissing(fld) Then
            Set baseFolder = fso.GetFolder(localRoot)
        Else
            Set baseFolder = fld
        End If

        For Each f In baseFolder.Files

            If IsMissing(ftpArray) Then
                ReDim ftpArray(0)
            Else
                i = UBound(ftpArray) + 1
                ReDim Preserve ftpArray(i)
            End If
            Set ftpFile = New FileInformation
            ftpFile.setValues localRoot, fso, f
            Set ftpArray(i) = ftpFile

        Next

        For Each subFolder In baseFolder.SubFolders
            getFileList localRoot, subFolder, ftpArray
        Next

        getFileList = ftpArray
    End Function