Break line on txt file is not desired - excel

This part of my code will save an excel file as txt file.
I select the range to be copied (in excel) to a new Workbook. This workbook will be saved as txt file. The range will always be a string with 15 columns and 1, 2 or 3 lines.
After being saved as txt file, this creates an extra break line after the pasted string. But i don't want that...
Can you help, please?
Sub Gravar_TXT()
Dim wb As Workbook
Dim saveFile As String
Dim RangeTXT As Range
On Error Resume Next
Dim wbEmail As Workbook, strGetFilename As String 'abrir ficheiro "encomenda"
strGetFilename = Application.GetOpenFilename(, , "Open Import Workbook")
Dim wsEmail As Worksheet, wsTXT As Worksheet
Set wbEmail = Workbooks.Open(strGetFilename)
Set wsTXT = wbEmail.Sheets("TXT")
'With wbEmail 'useless in your code context
wsTXT.Activate
xTitleId = "Selecionar Range para incluir no ficheiro TXT"
Set RangeTXT = Application.Selection
Set RangeTXT = Application.InputBox("Selecionar Range", xTitleId, RangeTXT.Address, Type:=8)
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Set wb = Application.Workbooks.Add
RangeTXT.Copy
With wb.Worksheets(1).Range("A1")
.PasteSpecial xlPasteColumnWidths
.PasteSpecial Paste:=xlPasteValuesAndNumberFormats
End With
saveFile = Application.GetSaveAsFilename(fileFilter:="Text Files (*.txt), *.txt")
wb.SaveAs FileName:=saveFile, FileFormat:=xlText, CreateBackup:=False
wb.Close
Application.CutCopyMode = False
Application.DisplayAlerts = True
Application.ScreenUpdating = True
'End With 'useless in your code context
End Sub
The "Final TXT file
Thank you

Use the next Sub, please:
Sub cleanTxtFile(fullFilename As String)
Dim objFSO As Object, objTF As Object, strTXT As String
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objTF = objFSO.OpenTextFile(fullFilename, 1)
strTXT = objTF.ReadAll
objTF.Close
'Clear the last two strTXT characters (CrLf):
strTXT = left(strTXT, Len(strTXT) - 2) 'clear the last character
'put back the arranged text:
Dim Fileout As Object
Set Fileout = objFSO.CreateTextFile(fullFilename, True, True)
Fileout.Write strTXT
Fileout.Close
End Sub
It will be called from inside your existing procedure:
'existing code...
'wb.SaveAs FileName:=saveFile, FileFormat:=xlText, CreateBackup:=False
wb.Close
'Here will be placed above Sub call:
cleanTxtFile saveFile
'your existing code...
Application.CutCopyMode = False
'...
I edited your question code and arranged a little from indentation point of view. I observed that the With wbEmail ... End With is useless in your code context and I commented these two lines.
Please try it and let me know if it works as you need, or further clarifications are necessary.

#FaneDuru...There's some issue with the code.
I've pasted like this:
'Here will be placed above Sub
Call cleanTxtFile 'saveFile
Application.CutCopyMode = False
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End With
End Sub
Sub cleanTxtFile(saveFile As String)
Dim objFSO As Object, objTF As Object, strTXT As String
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objTF = objFSO.OpenTextFile(saveFile, 1) 'After this step, it will return to the "main sub"
strTXT = objTF.ReadAll
objTF.Close
'Clear the last two strTXT characters (CrLf):
strTXT = Left(strTXT, Len(strTXT) - 2) 'clear the last character
'put back the arranged text:
Dim Fileout As Object
Set Fileout = objFSO.CreateTextFile(fullFilename, True, True)
Fileout.Write strTXT
Fileout.Close
End Sub

Related

Export to new workbook

When i use this code i get save as window and save workbook as i whish, but i also get one more workbook with active sheet from original, need help to get just one and if it is possible to close it after saving.
Code
Sub WorksheetSaveToNewWorkbook()
Dim loc As Variant
Dim Rng As Range
Dim newName As String
Dim newWkb As Workbook
Dim newWks As Worksheet
Dim Wks As Worksheet
Dim Shp As Shape
Application.DisplayAlerts = False
Set Wks = ThisWorkbook.ActiveSheet
Set Rng = Wks.Range("Q3:S170")
Data = Range("Q3:S170")
Wks.Copy
Set newWkb = Workbooks.Add
Set newWks = newWkb.ActiveSheet
With newWks
.Range("A1").Resize(UBound(Data, 1), UBound(Data, 2)).Value = Data
newName = " inklinometrija" & ".xlsx"
For Each Shp In .Shapes
Shp.OnAction = ""
Next Shp
loc = Application.GetSaveAsFilename(FileFilter:="Excel Files (*.xlsx), *.xlsx", Title:="Save As...", InitialFileName:=newName)
If loc <> False Then
ActiveWorkbook.SaveAs Filename:=loc, FileFormat:=xlOpenXMLWorkbook
Application.DisplayAlerts = True
Exit Sub
End If
Application.DisplayAlerts = True
End With
End Sub
Wks.Copy
Set newWkb = Workbooks.Add
Set newWks = newWkb.ActiveSheet
Wks.copy is in fact the code to create a new workbook with just that worksheet.

VBA - PasteSpecial Error and moving to next row in Excel

I am trying to loop through a number of word documents in a folder, and add some information from the word tables to the excel sheet. Right now I have this:
Private Sub Loop_WordToExcel()
Dim WdApp As Object
Dim wddoc As Object
Dim docName As String
Dim strFile As String
Dim directory As String
directory = "c:\path\to\folder"
strFile = Dir(directory & "*.*")
Set WdApp = CreateObject("Word.Application")
Dim rng As Range
Set rng = Application.InputBox(Prompt:="Enter row", Type:=8)
'Do While strFile <> ""
Set wddoc = WdApp.Documents.Open(Filename:=directory & strFile)
rng.Cells(1) = wddoc.Name
'First Name
wddoc.Tables(1).Cell(1, 3).Range.Copy
rng.Cells(2).PasteSpecial (xlPasteValues)
WdApp.ActiveDocument.Close SaveChanges:=False
strFile = Dir
Loop
End Sub
I have two questions.
1. My first issue is a Run-time error '1004': PasteSpecial method of Range class failed
2. At the end of the loop, how to I advance to the next row for the next word document information to be pasted.
Correct syntax while copying from Word is given, May try
Sub Loop_WordToExcel()
Dim WdApp As Word.Application
Dim WdDoc As Document
Dim docName As String
Dim strFile As String
Dim directory As String
Dim Rng As Range
Dim Offst As Long, Txt As String
directory = "C:\users\user\Desktop\Folder1\" ' Change to your path
strFile = Dir(directory & "*.docx") ' docx extension added to prevent attempt to open other type of files
Set Rng = Application.InputBox(Prompt:="Enter row", Type:=8) '
Set WdApp = CreateObject("Word.Application")
WdApp.Visible = True
Do While strFile <> ""
Set WdDoc = WdApp.Documents.Open(Filename:=directory & strFile)
Rng.Offset(Offst, 0).Value = WdDoc.Name
'First Name
WdDoc.Tables(1).Cell(1, 3).Range.Copy 'will raise error if table& corres cell not exists , My use error handrel
Rng.Offset(Offst, 1).Activate
ActiveSheet.PasteSpecial Format:="Text", Link:=False, DisplayAsIcon:=False 'Assumed want get name in Column B
'is is suggested to use the below two lines instead of paste special above three lines
'Txt = WdDoc.Tables(1).Cell(1, 3).Range.Text 'will raise error if table& corres cell not exists , My use error handrel
'Rng.Offset(Offst, 1).Value = Txt
WdDoc.Close SaveChanges:=False
Offst = Offst + 1
strFile = Dir
Loop
WdApp.Quit
End Sub
It is always preferred to add reference of Microsoft Word Object library.

Copy data from several Word documents to one Excel workbook using Word VBA

I have about 100 Word documents and from each I want to copy data and paste it all in one Excel workbook.
I came up with this code which opens one Word document, copies data, pastes it to Excel and closes the Word document:
Sub WordDataToExcel()
Dim myObj
Dim myWB
Dim mySh
Dim txt As String, Lgth As Long, Strt As Long
Dim i As Long
Dim oRng As Range
Dim Tgt As String
Dim TgtFile As String
Dim arr()
Dim ArrSize As Long
Dim ArrIncrement As Long
ArrIncrement = 1000
ArrSize = ArrIncrement
ReDim arr(ArrSize)
Dim wrdDoc As Object
Documents.Open ("D:\ekr5_i.doc")
TgtFile = "result.xlsx"
Tgt = "D:\" & TgtFile
'finds the text string of Lgth lenght
txt = "thetext"
Lgth = 85
Strt = Len(txt)
'Return data to array
With Selection
.HomeKey unit:=wdStory
With .Find
.ClearFormatting
.Forward = True
.Text = txt
.Execute
While .Found
i = i + 1
Set oRng = ActiveDocument.Range _
(Start:=Selection.Range.Start + Strt, _
End:=Selection.Range.End + Lgth)
arr(i) = oRng.Text
oRng.Start = oRng.End
.Execute
If i = ArrSize - 20 Then
ArrSize = ArrSize + ArrIncrement
ReDim Preserve arr(ArrSize)
End If
Wend
End With
End With
ReDim Preserve arr(i)
'Set target and write data
Set myObj = CreateObject("Excel.Application")
Set myWB = myObj.Workbooks.Open(Tgt)
Set mySh = myWB.Sheets(1)
With mySh
.Range(.Cells(1, 1), .Cells(i, 1)) = myObj.Transpose(arr)
End With
'Tidy up
myWB.Close True
myObj.Quit
ActiveDocument.Close SaveChanges:=wdDoNotSaveChanges
Set mySh = Nothing
Set myWB = Nothing
Set myObj = Nothing
End Sub
I need to loop through all the documents in the folder.
I have implemented the same with Excel workbooks, but I don't know how for Word documents.
Here is the code for Excel workbooks:
Sub combine_into_one()
Dim FSO As Object: Set FSO = CreateObject("Scripting.FileSystemObject")
Dim strPath$, Pivot$, sUserName$, sFolderName$, sSourceName$, x&
Dim oFldialog As FileDialog
Dim oFolder
Application.DisplayAlerts = False
Application.ScreenUpdating = False
Set oFldialog = Application.FileDialog(msoFileDialogFolderPicker)
With oFldialog
If .Show = -1 Then
.Title = "Select a Folder"
.AllowMultiSelect = False
.InitialFileName = strPath
sFolderName = .SelectedItems(1)
End If
End With
Set oFolder = FSO.GetFolder(sFolderName)
Workbooks.Add: Pivot = ActiveWorkbook.Name 'Destination workbook
For Each oFile In oFolder.Files
Workbooks(Pivot).Activate
x = Workbooks(Pivot).Sheets(1).Cells.SpecialCells(xlCellTypeLastCell).Row + 1
Workbooks.Open Filename:=oFile: sSourceName = ActiveWorkbook.Name
Workbooks(sSourceName).Activate
Workbooks(sSourceName).Sheets(1).[A80:Q94].copy
Workbooks(Pivot).Activate
Workbooks(Pivot).Sheets(1).Cells(x + 1, 1).PasteSpecial xlPasteAll
Workbooks(sSourceName).Close False
Next
Application.CutCopyMode = False
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub
There are so, so, so many things you can do between Excel & Word. I'm not sure I totally understand your question. The script below may help you; it has definitely served me well over time. If you need something different, please describe your issue more, to better clarify the issue you are facing.
Sub OpenAndReadWordDoc()
Rows("2:1000000").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.ClearContents
Range("A1").Select
' assumes that the previous procedure has been executed
Dim oWordApp As Word.Application
Dim oWordDoc As Word.Document
Dim blnStart As Boolean
Dim r As Long
Dim sFolder As String
Dim strFilePattern As String
Dim strFileName As String
Dim sFileName As String
Dim ws As Worksheet
Dim c As Long
Dim n As Long
'~~> Establish an Word application object
On Error Resume Next
Set oWordApp = GetObject(, "Word.Application")
If Err Then
Set oWordApp = CreateObject("Word.Application")
' We started Word for this macro
blnStart = True
End If
On Error GoTo ErrHandler
Set ws = ActiveSheet
r = 1 ' startrow for the copied text from the Word document
' Last column
n = ws.Range("A1").End(xlToRight).Column
sFolder = "C:\Users\Excel\Desktop\Coding\Microsoft Excel\PWC\Resumes\"
'~~> This is the extension you want to go in for
strFilePattern = "*.doc*"
'~~> Loop through the folder to get the word files
strFileName = Dir(sFolder & strFilePattern)
Do Until strFileName = ""
sFileName = sFolder & strFileName
'~~> Open the word doc
Set oWordDoc = oWordApp.Documents.Open(sFileName)
' Increase row number
r = r + 1
' Enter file name in column A
ws.Cells(r, 1).Value = sFileName
ActiveCell.Offset(1, 0).Select
ActiveSheet.Hyperlinks.Add Anchor:=Sheets("Sheet1").Range("A" & r), Address:=sFileName, _
SubAddress:="A" & r, TextToDisplay:=sFileName
' Loop through the columns
For c = 2 To n
If oWordDoc.Content.Find.Execute(FindText:=Trim(ws.Cells(1, c).Value), _
MatchWholeWord:=True, MatchCase:=False) Then
' If text found, enter Yes in column number c
ws.Cells(r, c).Value = "Yes"
End If
Next c
oWordDoc.Close SaveChanges:=False
'~~> Find next file
strFileName = Dir
Loop
ExitHandler:
On Error Resume Next
' close the Word application
Set oWordDoc = Nothing
If blnStart Then
' We started Word, so we close it
oWordApp.Quit
End If
Set oWordApp = Nothing
Exit Sub
ErrHandler:
MsgBox Err.Description, vbExclamation
Resume ExitHandler
End Sub
Function GetDirectory(path)
GetDirectory = Left(path, InStrRev(path, "\"))
End Function
In this scenario, whatever you put in the headers of B1:K1 (or more to the right) is searched for, each word document in a folder is opened, scanned, and if the string in B1:K1 is found, an 'x' is placed in the same x-y coordinate.
Again, if this doesn't help, please describe your issue better, and I'll post back with alternative solutions. Thanks!!

Copying a range from all files within a folder and pasting into master workbook

I'm fairly new to VBA so I apologize ahead of time. I've been getting involved with some complex operations and I would greatly appreciate some help or input.
With this macro, I am trying to:
Copy a specific range (2 column widths) from a specific sheet that is within all files in a given folder.
Paste the range values (and formatting if possible) in a column on the already open master workbook starting at B7 and moving over 2 columns for every new document so that the pasted data does not overlap.
Close files after copy/paste complete
As of right now I receive a
Run-time Error 9: Subscript out of range
for
Workbooks("RF_Summary_Template").Worksheets("Summary").Select
I know this is the least of my problems, though.
Below is my code:
Sub compile()
Dim SummaryFile As String, SummarySheet As String, summaryColumn As Long
Dim GetDir As String, Path As String
Dim dataFile As String, dataSheet As String, LastDataRow As Long
Dim i As Integer, FirstDataRow As Long
'********************************
RF_Summary_Template = ActiveWorkbook.Name 'summarybook
Summary = ActiveSheet.Name 'summarysheet
summaryColumn = Workbooks(RF_Summary_Template).Sheets(Summary).Cells(Columns.Count, 1).End(xlToLeft).Column + 1
CreateObject("WScript.Shell").Popup "First, browse to the correct directory, select ANY file in the directory, and click Open.", 2, "Select Install Base File"
GetDir = Application.GetOpenFilename("Excel Files (*.xls*), *.xls*")
If GetDir <> "False" Then
Path = CurDir & "\"
Else
MsgBox "Directory not selected"
Exit Sub
End If
Application.ScreenUpdating = False
dataFile = Dir(Path & "*.xls")
While dataFile <> ""
Workbooks.Open (dataFile)
Worksheets("Dashboard").Activate
ActiveSheet.Range("AY17:AZ35").Copy
Workbooks("RF_Summary_Template").Worksheets("Summary").Select
Range("B8").PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
Workbooks(dataFile).Close
summaryColumn = summaryColumn + 2
dataFile = Dir()
Wend
Workbooks(RF_Summary_Template).Save
Application.ScreenUpdating = True
End Sub
Thanks a million
I hope this helps. Run the procedure "CopyDataBetweenWorkBooks"
Sub CopyDataBetweenWorkbooks()
Dim wbSource As Workbook
Dim shTarget As Worksheet
Dim shSource As Worksheet
Dim strFilePath As String
Dim strPath As String
' Initialize some variables and
' get the folder path that has the files
Set shTarget = ThisWorkbook.Sheets("Summary")
strPath = GetPath
' Make sure a folder was picked.
If Not strPath = vbNullString Then
' Get all the files from the folder
strfile = Dir$(strPath & "*.xls", vbNormal)
Do While Not strfile = vbNullString
' Open the file and get the source sheet
Set wbSource = Workbooks.Open(strPath & strfile)
Set shSource = wbSource.Sheets("Dashboard")
'Copy the data
Call CopyData(shSource, shTarget)
'Close the workbook and move to the next file.
wbSource.Close False
strfile = Dir$()
Loop
End If
End Sub
' Procedure to copy the data.
Sub CopyData(ByRef shSource As Worksheet, shTarget As Worksheet)
Const strRANGE_ADDRESS As String = "AY17:AZ35"
Dim lCol As Long
'Determine the last column.
lCol = shTarget.Cells(8, shTarget.Columns.Count).End(xlToLeft).Column + 1
'Copy the data.
shSource.Range(strRANGE_ADDRESS).Copy
shTarget.Cells(8, lCol).PasteSpecial xlPasteValuesAndNumberFormats
' Reset the clipboard.
Application.CutCopyMode = xlCopy
End Sub
' Fucntion to get the folder path
Function GetPath() As String
With Application.FileDialog(msoFileDialogFolderPicker)
.ButtonName = "Select a folder"
.Title = "Folder Picker"
.AllowMultiSelect = False
'Get the folder if the user does not hot cancel
If .Show Then GetPath = .SelectedItems(1) & "\"
End With
End Function
I hope this helps :)
With the help of this code you can copy all workbooks and worksheets data
into one workbook
Sub copydata()
Dim fso As Scripting.FileSystemObject
Dim fill As Scripting.File
Dim oldfolder As String
Dim newfolder As String
Dim subfolder As Folder
Dim myfolder As Folder
Dim fd As FileDialog
Dim loopcount As Integer
Dim wb
Dim wb2 As Workbook
Dim rr As Range
Set fso = New Scripting.FileSystemObject
Set wb = ThisWorkbook
Set fd = Application.FileDialog(msoFileDialogFolderPicker)
fd.Title = "Please Select Folder to copy"
fd.ButtonName = "Go!"
fd.Show
oldfolder = fd.SelectedItems(1)
Set myfolder = fso.GetFolder(oldfolder)
'Application.ScreenUpdating = False
Application.EnableEvents = False
For Each subfolder In myfolder.SubFolders
For Each fill In subfolder.Files
If fill Like "*.xlsm" Or fill Like "*.xlsx" Or fill Like ".*xls" Then
'fill.Range("A1:Z100").Copy
Set wb2 = Application.Workbooks.Open(fill,0 , True)
wb2.Activate
For loopcount = 1 To wb2.Worksheets.Count
wb2.Activate
Worksheets(loopcount).Activate
Range("A1:Z300").Copy 'Replace your range
wb.Activate
Sheet1.Activate
Set rr = Range("A:A").Find("", Range("A1"))
rr.Select
ActiveSheet.Paste
ActiveCell.Offset(1, 0).Select
Next loopcount
wb2.Close False
End If
Application.CutCopyMode = False
Debug.Print fill.Name
Next fill
Next subfolder
MsgBox "Done"
For Each fill In myfolder.Files
Application.DisplayAlerts = False
If fill Like "*.xlsm" Or fill Like "*.xlsx" Or fill Like ".*xls" Or fill Like "*.xlsb" Then
'fill.Range("A1:Z100").Copy
Set wb2 = Application.Workbooks.Open(fill, 0, True)
wb2.Activate
For loopcount = 1 To wb2.Worksheets.Count
wb2.Activate
Worksheets(loopcount).Activate
Range("A:Z").EntireColumn.Hidden = False
Range("A1:Z1").AutoFilter
Range("A1:Z300").Copy
wb.Activate
Sheet1.Activate
Set rr = Range("A:A").Find("", Range("A1"))
rr.Select
ActiveSheet.Paste
ActiveCell.Offset(1, 0).Select
Next loopcount
wb2.Close False
End If
Application.CutCopyMode = False
Debug.Print fill.Name
Next fill
Application.EnableEvents = True
End Sub
Sub fdsdf()
'template is in the f_path
'files are under fpath\Raw Data\Ban
f_path = tree
Set wbTemplate = Workbooks.Open(Filename:=f_path & "\DEMAND_Template.xlsx")
MyFolder = f_path & "\Raw Data\Ban"
MyFile = Dir(MyFolder & "\*.xlsx")
Do While MyFile <> ""
Set wbIB = Workbooks.Open(Filename:=MyFolder & "\" & MyFile)
wbIB.Activate
Sheets("Sheet1").Select
r_cnt = ActiveSheet.UsedRange.Rows.Count
ran1 = "12:" & r_cnt
Rows(ran1).Select
Selection.Copy
wbTemplate.Select
Sheets("Sheet1").Select
r_cnt1 = ActiveSheet.UsedRange.Rows.Count
ran2 = Sheets("Sheet1").Range("A1048576").End(xlUp).Row + 1
Range("A" & ran2).Select
ActiveSheet.Paste
Application.CutCopyMode = False
wbIB.Close False
MyFile = Dir
Loop
wbTemplate.Save
End Sub
Sub final_consolidate()
f_path = "tree"
strFileToOpenIB = Application.GetOpenFilename(Title:="Please select the Consolidated file for Bangladesh", FileFilter:="Excel Files *.xlsx* (*.xlsx*),")
Set wbIB = Workbooks.Open(strFileToOpenIB)
wbIB.Activate
Sheets("Sheet1").Select
Sheets("Sheet1").Copy
wbIB.Activate
Sheets("Sheet2").Select
Sheets("Sheet2").Copy After:=Workbooks("Book1").Sheets(1)
wbIB.Activate
ActiveWorkbook.Close
Windows("Book1").Activate
strFileToOpenIB = Application.GetOpenFilename(Title:="Please select the Consolidated file for SriLanka", FileFilter:="Excel Files *.xlsx* (*.xlsx*),")
Set wbIB = Workbooks.Open(strFileToOpenIB)
wbIB.Activate
Sheets("Sheet1").Select
Sheets("Sheet1").Copy After:=Workbooks("Book1").Sheets(2)
wbIB.Activate
Sheets("Sheet2").Select
Sheets("Sheet2").Copy After:=Workbooks("Book1").Sheets(3)
wbIB.Activate
ActiveWorkbook.Close
Windows("Book1").Activate
ActiveWorkbook.SaveAs Filename:=f_path, FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False
End Sub

How to save particular column data of an excel worksheet to .txt file including line breaks in each cell content

I am pretty new to VBA. I have a requirement where I need to save the data in a particular column of an Excel worksheet (let's say used range of C column data) to a .txt file. After some web searching I got the VBA code, but the issue is, if a cell (say Cell(1,3)) is having data in multiple lines as shown below
Cell(1,3):
I got the VBA but I have a issue.
The VBA my using is saving the cell(1,3) content in a single line -'i got the vba but I have a issue help me out' I don't want it to be in a single line.
My requirement is very simple.
I have an activex button in the sheet.
when I click the button, data in C column must be saved to .txt file including line breaks. so if cell(1,3) has 4 lines and cell(2,3) has 2 lines then .txt file should have 6 lines. .txt file should exactly replicate my C column.
3.And this text file must be saved to "C"\vbacodes\" path.
Below is this code I found on internet
Private Sub CommandButton1_Click()
'Update 20130913Dim wb As Workbook
Dim saveFile As String
Dim WorkRng As Range
On Error Resume Next
xTitleId = "KutoolsforExcel"
Set WorkRng = Application.Selection
Set WorkRng = Application.InputBox("Range", xTitleId, WorkRng.Address, Type:=8)
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Set wb = Application.Workbooks.Add
WorkRng.Copy
wb.Worksheets(1).Paste
saveFile = Application.GetSaveAsFilename(fileFilter:="Text Files (*.txt), *.txt")
wb.SaveAs Filename:=saveFile, FileFormat:=xlText, CreateBackup:=False
wb.Close
Application.CutCopyMode = False
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub
First change the path and filename to match your requirements and then assign this macro to a button:
Sub TextFileMaker()
Dim MyFilePath As String, MyFileName As String
Dim N As Long, nFirstRow As Long, nLastrow As Long
MyFilePath = "C:\TestFolder\"
MyFileName = "whatever"
Set fs = CreateObject("Scripting.FileSystemObject")
Set a = fs.CreateTextFile(MyFilePath & MyFileName & ".txt", True)
nLastrow = Cells(Rows.Count, "C").End(xlUp).Row
nFirstRow = 1
For N = nFirstRow To nLastrow
t = Replace(Cells(N, "C").Text, Chr(10), vbCrLf)
a.WriteLine (t)
Next
a.Close
End Sub

Resources