You are currently viewing the Excel VBA section of the Wrox Programmer to Programmer discussions. This is a community of tens of thousands of software programmers and website developers including Wrox book authors and readers. As a guest, you can read any forum posting. By joining today you can post your own programming questions, respond to other developers’ questions, and eliminate the ads that are displayed to guests. Registration is fast, simple and absolutely free .
This module exports current region from worksheet to .csv file. Mayby it help You.
Sub ExportRange()
Dim FirstCol As Integer
Dim LastCol As Integer
Dim C As Integer
Dim FirstRow
Dim LastRow
Dim R
Dim data
Dim ExpRng As Range
Range("A1").Select
Set ExpRng = ActiveCell.CurrentRegion
FirstCol = ExpRng.Columns(1).Column
LastCol = FirstCol + ExpRng.Columns.Count - 1
FirstRow = ExpRng.Rows(1).Row
LastRow = FirstRow + ExpRng.Rows.Count - 1
Open ThisWorkbook.Path & "\textfile.csv" For Output As #1 ' csv file
'''''''Open ThisWorkbook.Path & "\textfile.txt" For Output As #1 '''''or txt file
For R = FirstRow To LastRow
For C = FirstCol To LastCol
data = ExpRng.Cells(R, C).Value
If data = "" Then data = ""
If IsNumeric(data) Then data = Val(data)
If C <> LastCol Then
Write #1, data;
Else
Write #1, data
End If
Next C
Next R
Close #1
End Sub
I have the next solution (I think that it is better)
Please read comments
Sub KOPIA1()
Dim NAME_OF_SHEET As String
NAME_OF_SHEET = Application.ActiveSheet.Name ' name of sheet which will be saved as .csv
Workbooks.Add
ActiveWorkbook.SaveAs ("C:\Documents and Settings\KAZIKL\Pulpit\" & NAME_OF_SHEET & ".xls") ' C:\Documents and Settings\KAZIKL\Pulpit\ path to temporary .xls file (You should change this patch)
Windows("KAZIK1.xls").Activate ' here put name of your file
Sheets(NAME_OF_SHEET).Select
Sheets(NAME_OF_SHEET).Copy Before:=Workbooks(NAME_OF_SHEET & ".xls").Sheets(1)
Sheets(Array("Arkusz1", "Arkusz2", "Arkusz3")).Select ' in English Sheet1, Sheet2 and Sheet3
Application.DisplayAlerts = False
ActiveWindow.SelectedSheets.Delete
ActiveWorkbook.SaveAs Filename:="C:\Documents and Settings\KAZIKL\Pulpit\" & NAME_OF_SHEET & ".csv", FileFormat:=xlCSV 'C:\Documents and Settings\KAZIKL\Pulpit\ path to .csv file (You should change this patch)
ActiveWorkbook.Save
ActiveWindow.Close
Windows("KAZIK1.xls").Activate
Kill ("C:\Documents and Settings\KAZIKL\Pulpit\" & NAME_OF_SHEET & ".xls") 'C:\Documents and Settings\KAZIKL\Pulpit\ path to temporary .xls file (You should change this patch)
Application.DisplayAlerts = True
End Sub