Exporting set of data to CSV file using worksheet name

jstarr

New Member
Joined
Dec 1, 2014
Messages
20
I currently have an excel spreadsheet that has a macro that I found in these forums built into it. The macro takes a range of data and exports it to save as a .csv file. It currently saves as the same name as the excel spreadsheet. How do I modify the macro in order to have the file save as the name of the worksheet that is being exported?
The macro being used is below:

Public Sub ExcelRowsToCSV()

Dim iPtr As Integer
Dim sFileName As String
Dim intFH As Integer
Dim aRange As Range
Dim iLastColumn As Integer
Dim oCell As Range
Dim iRec As Long

Set aRange = Range("P1:z200")
iLastColumn = aRange.Column + aRange.Columns.Count - 1

iPtr = InStrRev(ActiveWorkbook.FullName, ".")
sFileName = Left(ActiveWorkbook.FullName, iPtr - 1) & ".csv"
sFileName = Application.GetSaveAsFilename(InitialFileName:=sFileName, FileFilter:="CSV (Comma delimited) (*.csv), *.csv")
If sFileName = "False" Then Exit Sub

Close
intFH = FreeFile()
Open sFileName For Output As intFH

iRec = 0
For Each oCell In aRange
If oCell.Column = iLastColumn Then
Print #intFH, oCell.Value
iRec = iRec + 1
Else
Print #intFH, oCell.Value; ",";
End If
Next oCell

Close intFH

MsgBox "Finished: " & CStr(iRec) & " records written to " _
& sFileName & Space(10), vbOKOnly + vbInformation

End Sub
 

Excel Facts

How to calculate loan payments in Excel?
Use the PMT function: =PMT(5%/12,60,-25000) is for a $25,000 loan, 5% annual interest, 60 month loan.
Welcome to the Board!

Replace this:
Code:
[COLOR=#333333]iPtr = InStrRev(ActiveWorkbook.FullName, ".")[/COLOR]
[COLOR=#333333]sFileName = Left(ActiveWorkbook.FullName, iPtr - 1) & ".csv"[/COLOR]
with this:
Code:
sFileName = ActiveSheet.Name & ".csv"
 
Upvote 0

Forum statistics

Threads
1,223,237
Messages
6,170,928
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