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

Ambidextrous Undo
Undo last command with Ctrl+Z or Alt+Backspace. If you use the Undo icon in the QAT, open the drop-down arrow to undo up to 100 steps.
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,223,236
Messages
6,170,906
Members
452,366
Latest member
TePunaBloke

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