Example of a VBA custom function : data transfer to a text file


2007, Mar 12 edited
tags: VBA code Excel 


  A small and simple procedure, using some not so commonly used VBA functions. The aim : store a character string in a text file.

  This code allows the user to avoid using the usual Save As to text format file. This few lines of code perform the transfer of the string to a file.

  Warning : the code shown below works in a replace mode.




Warning



  The published files or code on Realce.net website are provided without any guarantee concerning their use. Realce.net is not responsible for the consequences of any use of these files. If you are not sure of what you are doing, ask a qualified person for help.

Thank you



Writing the procedure




'***************************************************
' Procedure : data2file
' Copyright Realce.net 2012 ' Objet : Save a character string into a text file ' Parameters :2 ' sdata : the string to be saved ' outfile : the file name , full path included ' version:0.02 Sub data2file(sdata As String, outfile As String) Errors processing On Error GoTo data2file_fin ' Macro command Open to perform I/O tasks on the files and more precisely in this cas writing in a file in the replace mode Open outfile For Output Access Write As #1 ' Writing the string in the file Print #1, sdata Close the file Close #1 Error data2file_fin: MsgBox ('Error') Close #1 End Sub ' *********************END***************************



Writing the Add_data2file custom function



And now the version with the add mode.


' ***************************************************
' Procedure : add_data2file
' Description : Save in append mode a character string in a text file (actualy at the en of the file)
' Parameters :2
'   sdata : the string to be saved
'   outfile : the full name of the file, path included
'  version:0.02

' ***************************************************
Sub add_data2file(sdata As String, outfile As String)
' Error processing
On Error GoTo add_data2file_fin
' Macro-command Open to perform I/O operations on files, in append mode in this case 
' Open outfile For Append Access  
Write  As #1
' Writing of the string
Print #1, sdata
Close the file
Close #1
Error
add_data2file_fin:
MsgBox ('Erreur')
Close #1
End Sub
*********************END***************************



To be continued



  Coming soon, other examples of vba usefull tools.
The fuel of coding inspiration:music, travel, photography and whatever drives creativity to code.

You might also like