Upload file via FTP from Excel VBA

后端 未结 5 632
栀梦
栀梦 2021-01-14 21:09

Need to upload a file (file.txt) to a server (ftp.server.com) from Excel VBA. (does not have to be necessarily FTP, just need to be able to put the file there and get it bac

5条回答
  •  梦谈多话
    2021-01-14 21:41

    After lot of research I found a method to upload file to FTP location without any .ocx file internet control file. This worked for me....

     Declare PtrSafe Function InternetConnect Lib "wininet.dll" Alias "InternetConnectA" ( _
            ByVal hInternetSession As Long, ByVal sServerName As String, _
            ByVal nServerPort As Integer, ByVal sUserName As String, _
            ByVal sPassword As String, ByVal lService As Long, _
            ByVal lFlags As Long, ByVal lContext As Long) As Long
        Declare PtrSafe Function InternetOpen Lib "wininet.dll" Alias "InternetOpenA" ( _
            ByVal sAgent As String, ByVal lAccessType As Long, _
            ByVal sProxyName As String, _
            ByVal sProxyBypass As String, ByVal lFlags As Long) As Long
        Declare PtrSafe Function FtpSetCurrentDirectory Lib "wininet.dll" Alias _
         "FtpSetCurrentDirectoryA" (ByVal hFtpSession As Long, _
            ByVal lpszDirectory As String) As Boolean
        Declare PtrSafe Function FtpPutFile Lib "wininet.dll" Alias "FtpPutFileA" ( _
            ByVal hConnect As Long, _
            ByVal lpszLocalFile As String, _
            ByVal lpszNewRemoteFile As String, _
            ByVal dwFlags As Long, _
            ByRef dwContext As Long) As Boolean
    
    Sub simpleFtpFileUpload()
    
        Dim ftp, FTP_PORT, user, password, loc_file, remote_file, ftp_folder As Variant
        ftp_folder = "/EXPORT"
        loc_file = ThisWorkbook.Path & "\readme.txt"
        remote_file = ftp_folder & "/readme.txt"
        FTP_PORT = "2221"
        user = "ajay"
        password = "ajay"
        ftp = "192.168.1.110"
    
        Internet_OK = InternetOpen("", 1, "", "", 0)
        If Internet_OK Then
            FTP_OK = InternetConnect(Internet_OK, ftp, FTP_PORT, user, password, 1, 0, 0) ' INTERNET_DEFAULT_FTP_PORT or port no
            If FtpSetCurrentDirectory(FTP_OK, "/") Then
                Success = FtpPutFile(FTP_OK, loc_file, remote_file, FTP_TRANSFER_TYPE_BINARY, 0)
            End If
        End If
        If Success Then
            Debug.Print "ftp success ;)"
            MsgBox "ftp success ;)"
        Else
            Debug.Print "ftp failure :("
            MsgBox "ftp failure :("
        End If
    End Sub
    

    Please change values as per your needs

        ftp_folder = "/EXPORT"
        loc_file = ThisWorkbook.Path & "\readme.txt"
        remote_file = ftp_folder & "/readme.txt"
        FTP_PORT = "2221"
        user = "ajay"
        password = "ajay"
        ftp = "192.168.1.110"
    

提交回复
热议问题