PDA

View Full Version : [SOLVED:] Saving as .csv



Kaizer
05-18-2005, 06:36 AM
Hi guys,
below is the part of the code when I am taking the data from a sheet and save it as *.csv file.


'Export data
vFF = FreeFile
Open vSaveFile For Output As #vFF
Print #vFF, Sheets(2).Range("A1").Text 'line 1
Print #vFF, CStr(Month(Sheets(2).Range("A2"))) 'line 2
Print #vFF, CStr(Month(Sheets(2).Range("A2"))) 'line 3
Print #vFF, "Actual" 'line 4
For i = 0 To ExpCount - 2
Print #vFF, ExpAcct(i) 'lines 5 through second last account
Next i
Print #vFF, ExpAcct(ExpCount - 1); 'last account ends in ; to prevent extra line feed
Close #vFF

Now, I need to change it a little.
Sheets(2).Range("A1").Text in line 1 will be in Column A of my *.csv file. I need to add some value in line 1 that will be in Column B of my *.csv file. How to do it?

Thanks in advance.

Bob Phillips
05-18-2005, 07:01 AM
Do you mean?


Sheets(2).Range("B1").Text

Kaizer
05-18-2005, 07:10 AM
It can be
Sheets(2).Range("B1").Text but in my case it will be a string="Actual".

Norie
05-18-2005, 07:19 AM
How is this code saving as a CSV?

Kaizer
05-18-2005, 07:23 AM
OK, here is the complete code:




Sub KaizerExportCSV()
Dim vFF As Long, vSaveFile As String
Dim AllAcctData, ExpAcct() As String, ExpCount As Long, i As Long
Dim RG As Range
'Account data range, starting in row 2 to account for headers
Set RG = Intersect(Sheets(1).Range("A2:B65536"), Sheets(1).UsedRange)
If RG Is Nothing Then Exit Sub 'no data on sheet 1
AllAcctData = RG.Value
'Create array of data to export, using only non-zero and non-blank account values
ExpCount = 0
For i = LBound(AllAcctData, 1) To UBound(AllAcctData, 1)
If AllAcctData(i, 2) <> 0 And AllAcctData(i, 2) <> "" Then
ReDim Preserve ExpAcct(ExpCount)
ExpAcct(ExpCount) = AllAcctData(i, 1) & "," & AllAcctData(i, 2)
ExpCount = ExpCount + 1
End If
Next i
If ExpCount = 0 Then Exit Sub 'No non-zero values
'Get save file name
vSaveFile = Application.GetSaveAsFilename(InitialFilename:=Left(ActiveWorkbook.Name, _
Len(ActiveWorkbook.Name) - 4) & ".csv", filefilter:="CSV Files,*.csv,All Files,*.*")
If LCase(vSaveFile) = "false" Then Exit Sub 'user hit cancel
'Export data
vFF = FreeFile
Open vSaveFile For Output As #vFF
Print #vFF, Sheets(2).Range("A1").Text 'line 1
Print #vFF, CStr(Month(Sheets(2).Range("A2"))) 'line 2
Print #vFF, CStr(Month(Sheets(2).Range("A2"))) 'line 3
Print #vFF, "Actual" 'line 4
For i = 0 To ExpCount - 2
Print #vFF, ExpAcct(i) 'lines 5 through second last account
Next i
Print #vFF, ExpAcct(ExpCount - 1); 'last account ends in ; to prevent extra line feed
Close #vFF
End Sub

Ken Puls
05-18-2005, 08:26 AM
Hi Kaizer,

I've edited your post to use our VBA tags. a. (No need to do all the colouring yourself!)

HTH,

Kaizer
05-19-2005, 10:36 AM
I have found the way to treat this operation. No worries.