Experts needed! Macro to FTP a file and overwrite existing if needed

Oliver Dewar

Board Regular
Joined
Apr 17, 2011
Messages
201
Hi All.

I'm trying to create a macro that will upoad a .csv file to a folder on my website.

I found loads of different version of code to do this and I can't get any of them to work.

I admit right here that I am only as much of an expert in this as Googling for 4 hours can make you... so not ;)

This code seems like the most trusted and best from what I can see:

Code:
Sub PublishFile()
Dim strDirectoryList As String
Dim lStr_Dir As String
Dim lInt_FreeFile01 As Integer
Dim lInt_FreeFile02 As Integer
On Error GoTo Err_Handler
    lStr_Dir = ThisWorkbook.Path
    lInt_FreeFile01 = FreeFile
    lInt_FreeFile02 = FreeFile
    '' ANW  07-Feb-2003 :
    strDirectoryList = lStr_Dir & "\Directory"
    '' Delete completion file
    If Dir(strDirectoryList & ".out") <> "" Then Kill (strDirectoryList & ".out")
    '' Create text file with FTP commands
    Open strDirectoryList & ".txt" For Output As #lInt_FreeFile01
    Print #lInt_FreeFile01, "open [URL="ftp://ftp.mysite.com"]ftp.mysite.com[/URL]"
    Print #lInt_FreeFile01, "myusername"
    Print #lInt_FreeFile01, "mypassword"
    Print #lInt_FreeFile01, "cd Website-Search/"
    Print #lInt_FreeFile01, "binary"
    Print #lInt_FreeFile01, "put """ & ThisWorkbook.Path & "\System\Website-Search-File\Website-Search.csv"""
    '' To receive a file, replace the above line with this one
    ''Print #lInt_FreeFile01, "recv \Picture.gif " & ThisWorkbook.Path & "\Picture.gif"
    
    Print #lInt_FreeFile01, "bye"
    Close #lInt_FreeFile01
    '' Create Batch program
    Open strDirectoryList & ".bat" For Output As #lInt_FreeFile02
    Print #lInt_FreeFile02, "ftp -s:" & strDirectoryList & ".txt"
    Print #lInt_FreeFile02, "Echo ""Complete"" > " & strDirectoryList & ".out"
    Close #lInt_FreeFile02
    '' Invoke Directory List generator
    Shell (strDirectoryList & ".bat"), vbHide '', vbMinimizedNoFocus
    'Wait for completion
    Do While Dir(strDirectoryList & ".out") = ""
        DoEvents
    Loop
    Application.Wait (Now + TimeValue("0:00:03"))
    '' Clean up files
    If Dir(strDirectoryList & ".bat") <> "" Then Kill (strDirectoryList & ".bat")
    If Dir(strDirectoryList & ".out") <> "" Then Kill (strDirectoryList & ".out")
    If Dir(strDirectoryList & ".txt") <> "" Then Kill (strDirectoryList & ".txt")
bye:
Exit Sub
Err_Handler:
    MsgBox "Error : " & Err.Number & vbCrLf & "Description : " & Err.Description, vbCritical
    Resume bye
End Sub


The .txt file it produces looks like this:


Code:
[SIZE=2]open [URL="ftp://ftp.mysite.com"]ftp.mysite.com[/URL]
[EMAIL="lessons@starsandcatz.com.au"]myusername[/EMAIL]
mypassword
cd Website-Search/
binary
put "C:\Users\User\Dropbox\System\Shells\Australia\System\Website-Search-File\Website-Search.csv"
bye
[/SIZE]


When I run this two files named Directory are created 1 text doc and one bat file. But the code hangs on DoEvents (just after 'Wait for completion) and the file doesn't appear in my website directory.

I think I'm doing something simple wrong but I've tried lots of variations of file addresses etc.

Can anyone see the noobie error I'm making and help me nail it?

Also - assuming I get this working, will I need an extra command to overwrite an existing file of the same name, or will this happen automatically?

All help will be much appreciated.

Cheers,

Oliver
 
Last edited:

Excel Facts

Will the fill handle fill 1, 2, 3?
Yes! Type 1 in a cell. Hold down Ctrl while you drag the fill handle.
Code:
    Print #lInt_FreeFile01, "cd Website-Search/"
I'm not sure if the slash is in the right place there. Maybe it should be one of these:

cd /WebSite-Search
cd WebSite-Search

or even one of these (it depends on your particular ftp server and whether you are trying to upload to a publicly accessible folder):

cd public/Website-Search
cd public_html/Website-Search

Whichever is correct, try the following code instead. This creates only 1 temporary file in contrast to the 3 that your code creates. Make sure you edit the code at the top to change the ftp server string to suit. The rest of the code shouldn't need changing.
Code:
Const cFTPServer As String = "ftp.mysite.com"     'CHANGE THIS.
Const cFTPPort = 21
Const cFTPCommandsFile As String = "FTP_commands.txt"


Public Sub Ftp_Upload_File()

    Dim inputValue As Variant
    Dim FTPusername As String, FTPpassword As String
    Dim filenum As Integer
    Dim FTPcommand As String
    Dim wsh As Object
    
    inputValue = InputBox("Enter username", cFTPServer)
    If inputValue = False Or inputValue = "" Then Exit Sub
    FTPusername = CStr(inputValue)
    
    inputValue = InputBox("Enter password for username " & FTPusername, cFTPServer)
    If inputValue = False Or inputValue = "" Then Exit Sub
    FTPpassword = CStr(inputValue)
    
    'Create file containing ftp commands.  The file has to contain the username and password
    'to connect to the ftp server.  Creating the file and deleting it immediately after use gives some degree of
    'security in preference to having a static file containing the username and password
    
    filenum = FreeFile
    Open cFTPCommandsFile For Output As #filenum
    Print #filenum, "!REM upload .csv file"             'Use !REM for comments with a Windows ftp server
    'Print #filenum, "!# upload .csv file"              'Use '# for comments with a Unix ftp server
    Print #filenum, "open " & cFTPServer & " " & cFTPPort
    Print #filenum, "user " & FTPusername & " " & FTPpassword
    Print #filenum, "cd Website-Search"
    Print #filenum, "binary"
    Print #filenum, "put " & QQ(ThisWorkbook.Path & "\System\Website-Search-File\Website-Search.csv")
    
    'The next line is temporarily commented out to omit the bye command from the ftp commands script.
    'This keeps the command window open to show whether the ftp commands worked successfully or not.
    'If the bye command is omitted you must type bye in the command window to exit ftp and end this procedure
    
    'Print #filenum, "bye"
    Close #filenum
    
    'Construct ftp command line, specifying the file containing FTP commands.  The -n parameter suppresses auto-login
    'upon initial connection because we want to use the username and password specified in the command file
    
    FTPcommand = "ftp -i -n -s:" & QQ(cFTPCommandsFile)
    
    'Run ftp command synchronously, waiting for the command to return
    'WindowStyle 1 displays the command window. Use this, together with omitting the bye command, to verify
    'whether or not the ftp commands worked successfully.
    'WindowStyle 0 hides the command window.
    'See http://msdn.microsoft.com/en-us/library/d5fk67ky%28VS.85%29.aspx
    
    CreateObject("WScript.Shell").Run Command:=FTPcommand, WindowStyle:=1, waitonreturn:=True
        
    'Delete the ftp commands file so that the username and password are not left lying around
    
    Kill cFTPCommandsFile
    
    MsgBox "Finished"
            
End Sub

Private Function QQ(text As String) As String
    QQ = Chr(34) & text & Chr(34)
End Function
will I need an extra command to overwrite an existing file of the same name, or will this happen automatically?
The ftp put command should overwrite an existing file.
 
Upvote 0

Forum statistics

Threads
1,223,164
Messages
6,170,444
Members
452,326
Latest member
johnshaji

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top