Rivers31334
Rivers31334

Reputation: 654

reading a csv file into a text file

I am at work trying to solve a few issues. I have a large .csv file that has 4 columns (first name, last name, identifying number, gender) and many rows with corresponding individuals. I don't use VBA but am trying to write a macro that reads the excel file and places the data into a txt file with a space delimiter.

I used a website tutorial and came up with teh following, however, it seems so wrong.

Sub test()

Dim myFile As String
Dim rng As Range
Dim cellvalue As Variant
Dim i As Integer
Dim j As Integer

myFile = Application.DefaultFilePath & "\Book1.csv"

Set rng = Selection

Open myFile For Output As #1

For i = 1 To rng.Rows.Count
For j = 1 To rng.Columns.Count
    cellvalue = rng.Cells(i, j).Value

    If j = rng.Columns.Count Then
        Write #1, cellvalue
    Else
        Write #1, cellvalue,
    End If

Next j
Next i

Close #1

End Sub

The idea was to put a command button in the excel file, write this code, assign the macro to the button, select the data in question, and hit the button. If anyone is willing to help a new guy, appreciation will be yours.

Upvotes: 2

Views: 1135

Answers (1)

This tutorial will be ok for this: http://www.excel-easy.com/vba/examples/write-data-to-text-file.html

Change Write #1 for Print #1

Upvotes: 2

Related Questions