Quantcast
Channel: Excel Help Forum - Excel Programming / VBA / Macros
Viewing all articles
Browse latest Browse all 50167

Macro to create text file and write contents of selected cells to the file

$
0
0
Hello,

I need some help writing the contents of specific cells to a newly created text file that's named with the contents of a cell. (That doesn't sound very clear, does it?) I'll explain. I have a large worksheet with data in multiple rows and columns A-J. The macro will prompt the user to select a cell and then create a text file using the contents of the cell as the name. This part works fine based on some code I found on other sites. The next step is to write the contents of the same sell into the file along with the contents of cells D and F in the same row, separated by commas. I can get the contents of the first cell written but when I try to write the contents from another cell the file ends up being blank. I'm not sure if it's how I'm declaring the other variables or what. This is the portion I have working correctly.

Code:

Sub CreateTxtFile()
'
'Sets the path to the text file directory
MyPath = "C:\temp\"

'Requests the user to select the cell to create file from

Set MyCell = Application.InputBox( _
    prompt:="Select the cell that you want to create text file", Type:=8)
    MyCell.Select

MyText = MyCell.Text

If Not Len(MyText) = 0 Then

f = FreeFile

Open MyPath & MyText & ".txt" For Output As f

Print #f, MyCell & ","

Close f

End If

End Sub

Any help or pointers would be much appreciated.

Viewing all articles
Browse latest Browse all 50167

Trending Articles