I need to copy cells from a worksheet and paste them into a .txt file

15 pts.
Tags:
.txt file
copy
paste

I am very new to this whole VBA thing so I need elementary explanation on how to copy a range of cells from a worksheet A1:G50 and paste them into a .txt file using a macro. Im sure it can be done but all my efforts have been in vain. If possible Id like the macro to create the .txt file,then paste the range into it as well as name the file Port Log 1. Any help would be tremendously appreciated as im usually able to figure these problems out on my own. But this one is way above my skill level.

Answer Wiki

Thanks. We'll let you know when a new response is added.

Here is a very basic example.  It will surely need some modifications, but at least it should help you get started.

Sub WriteFile()
    Dim rMyRange As Range
    Dim sFileName As String
    Dim sRowData As String
    Dim iCurrentRow
    
    Set rMyRange = Range("A1:G50")
    sFileName = Application.DefaultFilePath & "\PortLog1.txt"
    
    Open sFileName For Output As #1
    iCurrentRow = 0
    
    For Each cell In rMyRange
        If iCurrentRow <> cell.Row Then
            Write #1, sRowData
            sRowData = cell.Value
        Else
            sRowData = sRowData & "," & cell.Value
        End If
        iCurrentRow = cell.Row
    Next cell
    Write #1, sRowData
    
    Close #1
End Sub

Discuss This Question: 2  Replies

 
There was an error processing your information. Please try again later.
Thanks. We'll let you know when a new response is added.
Send me notifications when members answer or reply to this question.

REGISTER or login:

Forgot Password?
By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy
  • seahawk416
    Thank you,definately gave me some insight as to the correct paths. Ill massage the code some to get it to fit exactly. Sorry it took so long to reply and thank you for your help.
    15 pointsBadges:
    report
  • carlosdl
    No problem.  I'm glad it was helpful.
    70,220 pointsBadges:
    report

Forgot Password

No problem! Submit your e-mail address below. We'll send you an e-mail containing your password.

Your password has been sent to:

To follow this tag...

There was an error processing your information. Please try again later.

REGISTER or login:

Forgot Password?
By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy

Thanks! We'll email you when relevant content is added and updated.

Following