Sub CopySortAndExportToTxt()
Dim sourceSheet As Worksheet
Dim sourceRange As Range
Dim newWorkbook As Workbook
Dim sortedRange As Range
Dim lastDataRow As Long
Dim filePath As String
' Define the source sheet and range in the current workbook
Set sourceSheet = ThisWorkbook.Sheets("Sheet1") ' Update with your sheet name
lastDataRow = sourceSheet.Cells(sourceSheet.Rows.Count, "A").End(xlUp).Row
Set sourceRange = sourceSheet.Range("A1:B" & lastDataRow)
' Create a new workbook
Set newWorkbook = Workbooks.Add
' Copy the source range to the new workbook
sourceRange.Copy Destination:=newWorkbook.Sheets(1).Range("A1")
' Sort the data in the new workbook (assuming sorting by the first column)
With newWorkbook.Sheets(1).Sort
.SortFields.Add Key:=Range("A1"), Order:=xlAscending
.SetRange newWorkbook.Sheets(1).UsedRange
.Header = xlYes
.Apply
End With
' Define the sorted range
Set sortedRange = newWorkbook.Sheets(1).UsedRange
' Define the file path and name for the text file
filePath = "C:\Path\To\Your\File.txt" ' Update this with your desired file path
' Export the sorted range to a text file
sortedRange.SaveAsText filePath, xlTextWindows
' Close the new workbook without saving changes
newWorkbook.Close SaveChanges:=False
MsgBox "Data has been sorted and exported to " & filePath, vbInformation
End Sub