0% found this document useful (0 votes)
6 views1 page

Sub CopySortAndExportToTxt

This VBA code copies a range from a source sheet, pastes it into a new workbook, sorts the data, defines the sorted range, and saves it as a text file to a specified file path.

Uploaded by

Leontin Niţu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views1 page

Sub CopySortAndExportToTxt

This VBA code copies a range from a source sheet, pastes it into a new workbook, sorts the data, defines the sorted range, and saves it as a text file to a specified file path.

Uploaded by

Leontin Niţu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 1

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

You might also like