vba save file as txt file

JMARIE5

New Member
Joined
Feb 28, 2022
Messages
2
Office Version
  1. 365
Platform
  1. Windows
Hello,

I am new here and still learning VBA. I am struggling with my code.
I have multiple sheets that I need to save as a txt file in the same workbook. However, the code is only working when the sheet is selected. Can someone help me out with my code?

Sub DOTtxt()


Dim wb As ThisWorkbook
Set wb = ThisWorkbook
Dim j As Long

Dim ws As Worksheet
Set ws = wb.Sheets("DOT")

Dim fso As Scripting.FileSystemObject
Set fso = New Scripting.FileSystemObject

Dim my_textfile As Scripting.TextStream
Set my_textfile = fso.CreateTextFile("file path to my folder.txt")

Dim rownum As Long, var As Variant
rownum = 2

For j = 2 To Range("a1000000").End(xlUp).Row


var = Cells(rownum, 1).Value

'going to write in the text file create above
my_textfile.WriteLine var

rownum = rownum + 1


Next

my_textfile.Close


End Sub
 

Excel Facts

Get help while writing formula
Click the italics "fx" icon to the left of the formula bar to open the Functions Arguments dialog. Help is displayed for each argument.
you could copy that range to an empty sheet and then copy that sheet to a new workbook and save that new workbook as txt or csv with this macro
VBA Code:
sub test
PathName = "C:\test.csv"
'Assuming you want to export your current Worksheet
ActiveSheet.Move 'Move the Worksheet to a new Workbook
ActiveWorkbook.SaveAs Filename:=PathName, FileFormat:=xlCSV, CreateBackup:=False
end sub
 
Upvote 0
Keep it simple. This one-liner saves the active sheet as a tab-delimited text file.

VBA Code:
ActiveWorkbook.SaveAs Filename:="C:\path\filename.txt", FileFormat:=xlTextMSDOS
 
Upvote 0
Solution

Forum statistics

Threads
1,214,976
Messages
6,122,541
Members
449,089
Latest member
davidcom

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