Exporting Data into a CSV - Excel VBA - vba

Say I have a function that generates some data into cells into the current worksheet like :
Cells(1, "A").Value = ...
Cells(2, "A").Value = ...
Cells(3, "A").Value = ...
Cells(4, "A").Value = ...
Instead of the being the current worksheet in the current workbook, I want to create and load it into a csv file, to a give path
Say C:\USERS\Documents\Sample.csv.
I've seen stuff like
ActiveWorkbook.SaveAs Filename:= _
"c:\MyFile.csv", FileFormat:=xlCSV _
, CreateBackup:=False
But this will just save the current workbook to another location, but I don't want to generate data in the current worksheet and then save, rather I want to export right away? Is there anyway I can do that. Maybe making like ActiveWorkbook = //pathname and then Activating it ?

You can write to a CSV quite simply using VBA.
An example could be:
Sub WriteCSVFile()
Dim My_filenumber As Integer
Dim logSTR As String
My_filenumber = FreeFile
logSTR = logSTR & Cells(1, "A").Value & " , "
logSTR = logSTR & Cells(2, "A").Value & " , "
logSTR = logSTR & Cells(3, "A").Value & " , "
logSTR = logSTR & Cells(4, "A").Value
Open "C:\USERS\Documents\Sample.csv" For Append As #My_filenumber
Print #My_filenumber, logSTR
Close #My_filenumber
End Sub

Use the .move to make a new book of the target sheet, then .saveas the newly created book as a CSV. Adjust the Pathname to adjust the directory where you want your csv saved.
Pathname = "" & Thisworkbook.path & "YourName.csv"
Sheets("Sheet you want as CSV").Move
ActiveWorkbook.SaveAs Filename:=PathName, _
FileFormat:=xlCSV, CreateBackup:=False

Just modified the code by #CharlieSmith to a fairly simple and more usable code, which will convert all the sheets in your workbook to new csv files named with respective sheet names.
Sub WriteCSVFile()
Dim i As Integer
Dim WS_Count As Integer
WS_Count = ActiveWorkbook.Worksheets.Count
For i = 1 To WS_Count
Dim ws As Worksheet
Set ws = ThisWorkbook.Worksheets(i)
PathName = "" & ThisWorkbook.Path & "\" & ws.Name & ".csv"
ws.Copy
ActiveWorkbook.SaveAs Filename:=PathName, _
FileFormat:=xlCSV, CreateBackup:=False
Next i
End Sub
Hope this helps

Related

VBA - can not save as "xlsx" from "xlsm"

Me again , I'm trying to code for spliting sheets in the xlsm file into the seperate sheet then save them in the same place with the xlsm file. the code as below:
Sub splitsheet()
Dim path As String
Dim cities
ReDim cities(1 To ThisWorkbook.Worksheets.Count)
Dim i As Long
Dim sh As Worksheet
path = ActiveWorkbook.path
For i = 1 To Worksheets.Count
cities(i) = Sheets(i).Name
ActiveWorkbook.SaveAs _
Filename:=path & "\" & Sheets(i).Name & ".xlsx"
'ActiveWorkbook.Close False
Next i
End Sub
The error in my photo below. Why it can not save as in "xlsx" extension , above code is work fine with "xlsm" extension
Filename:=path & "\" & Sheets(i).Name & ".xlsm" 'it can work fine with xlsm extension
My question is how can save as in "xlsx" extension in this case. All assist/explaination will be appriciated.
Please try this code.
Sub EachSheetToEachOwnWorkbook()
' 286
Dim Path As String
Dim Ws As Worksheet
Application.ScreenUpdating = False
Path = ThisWorkbook.Path & "\"
For Each Ws In ThisWorkbook.Worksheets
Ws.Copy
With ActiveWorkbook
.SaveAs Filename:=Path & Ws.Name & ".xlsx", _
FileFormat:=xlOpenXMLWorkbook, _
CreateBackup:=False
.Close
End With
Next Ws
Application.ScreenUpdating = True
End Sub

VBA code:Save the fillter data to txt file

VBA code: help me with, I want to save the fillter data to txt file.
Sub Intemp()
Dim arr, i As Long
Dim FPath As String
FPath = ThisWorkbook.Path & "\" & "text" & ".txt"
Application.CutCopyMode = False
arr = Sheet5.Range("B1:C" & [B100000].End(xlUp).Row)
Open FPath For Output As #1
For i = 1 To UBound(arr)
Print #1, arr(i, 1) & vbTab & arr(i, 2)
Next i
Close #1
End Sub
If you want to assign your filtered values to an array, an easy way to do that would be to use advanced filtering and filter into another area of the worksheet and assign your values there.
But a simple approach that will get you started is to just loop your rows in your range, if the row is hidden, then move on - otherwise, print the data to your text document.
Dim rng As Range, r As Long
Set rng = Sheet5.Range("B1:C" & [B100000].End(xlUp).Row)
Dim FPath As String
FPath = ThisWorkbook.Path & "\" & "text" & ".txt"
Application.CutCopyMode = False
Open FPath For Output As #1
With Sheet5
For r = rng.Row To rng.Rows.Count + rng.Row - 1
If Not .Rows(r).Hidden Then
Print #1, .Cells(r, 1) & vbTab & .Cells(r, 2)
End If
Next
End With
Close #1

Rearranging columns and exIporting range to CSV

I have a set of data that is downloaded from SQL Server. Data can be huge. I need to rearrange it to a specific column order template before exporting it to either CSV or XLSX, really does not matter.
In this instance, I have put together a code that takes the original data (From Col A to Co; Q and set them up in the same sheet from Col T to Col AB) then attempt to export that range (T:AB to Last row) as CSV.
First part of the code works, pretty straightforward. However, I am struggling to export the range to either CSV or XLSX. Currently it is exporting data into another file only in row 1.
CODE
Sub test()
Dim LR As Long
Dim myCSVFileName As String
Dim myWB As Workbook
Dim rngToSave As range
Dim fNum As Integer
Dim csvVal As String
LR = Sheets("AAP").Cells(Rows.count, "A").End(xlUp).row
Sheets("AAP").range("T2:T" & LR).Value = Sheets("AAP").range("B2:B" & LR).Value
Sheets("AAP").range("U2:U" & LR).Value = Sheets("AAP").range("C2:C" & LR).Value
Sheets("AAP").range("V2:V" & LR).Value = Sheets("AAP").range("I2:I" & LR).Value
Sheets("AAP").range("W2:W" & LR).Value = Sheets("AAP").range("J2:J" & LR).Value
Sheets("AAP").range("X2:X" & LR).Value = Sheets("AAP").range("E2:E" & LR).Value
Sheets("AAP").range("Y2:Y" & LR).Value = Sheets("AAP").range("F2:F" & LR).Value
Sheets("AAP").range("Z2:Z" & LR).Value = Sheets("AAP").range("H2:H" & LR).Value
Sheets("AAP").range("AA2:AA" & LR).Value = Sheets("AAP").range("G2:G" & LR).Value
Sheets("AAP").range("AB2:AB" & LR).Value = "AA_FEES"
Set myWB = ThisWorkbook
myCSVFileName = myWB.Path & "\" & "CSV-Exported-File-" & VBA.Format(VBA.Now, "dd-MMM-yyyy hh-mm") & ".csv"
csvVal = ""
fNum = FreeFile
Set rngToSave = range("T2:AB" & LR)
Open myCSVFileName For Output As #fNum
For i = 1 To rngToSave.Rows.count
For j = 1 To rngToSave.Columns.count
csvVal = csvVal & Chr(34) & rngToSave(i, j).Value & Chr(34) & ","
Next
Print #fNum, Left(csvVal, Len(csvVal) - 2)
csvVal = ""
Next
Close #fileNumber
End Sub
Any advise how to make this more efficient would be greatly appreciated.
The easiest method to export that to a CSV would be to copy the worksheet to no destination. This creates a new workbook that is the new ActiveWorkbook with a single worksheet that is a copy of the original. After deleting columns A:S, SaveAs xlCSV.
...
workSheets("AAP").copy
with activeworkbook
application.displayalerts = false
.worksheets(1).range("A:S").entirecolumn.delete
.saveas filename:=myCSVFileName, fileformat:=xlcsv
.close savechanges:=false
application.displayalerts = true
end with

my code runs and works on some excel workbooks but not all of them, why? VBA

I have a weird problem with my code VBA.
I am using excel 2010, i wrote a code which works perfectly on multiple source except some.
my code object is to copy the same cell from the same sheet from multiple workbooks and paste it into a destination workbook as a column.
My code runs on 50 workbooks without any problem, except 2.
Notice that those 2 are the same sample as the others, but of course different values.
If I ad those 2 workbooks with the other 50, I have an error message 'Error of execution'1004' and I should then stop the process.
the yellow line stand on a the formula :
myFile = Dir(myPath & myExtension)
Set y = Workbooks.Open(destFullpath)
`With y.Sheets("Feuil1").Range("A" & i + 1)
**.Formula = "='" & "[" & myFile & "]Para RF'!L2" 'date**
.Value = .Value
y.Sheets("Feuil1").Range("A" & i + 1).NumberFormat = "dd/mm/yy;#" ' <-- to specify that it is a date format
End With`
Do you have an idea why can this problem occur?
what should i do? Is there anything to change with the settings etc?
Note That I have tried to save those 2 as excel without macros, so xlsx and did not run.
I tried to unprotect the sheets: did not run
I broke the link between them and other one: this didn't help either!!!
what can it be??
Thank you!!
This is the entire code :
Sub LoopAllExcelFilesInFolderr()
'PURPOSE: To loop through all Excel files in a user specified folder and
perform a set task on them
Dim wb As Workbook
Dim myPath As String
Dim myFile As String
Dim destFullpath As String
Dim myExtension As String
DimFldrPicker As FileDialog
Dim y As Workbook
Dim i As Integer
'Optimize Macro Speed
Application.ScreenUpdating = False
Application.EnableEvents = False
Application.Calculation = xlCalculationManual
'Application.DisplayAlerts = False
'Retrieve Target Folder Path From User
myPath = "Z:\VBA\para_macro\"
destFullpath = "Z:\VBA\base-macro.xlsx"
If myPath = "" Then GoTo ResetSettings
'Target File Extension (must include wildcard "*")
myExtension = "*.xls*"
'Target Path with Ending Extention
myFile = Dir(myPath & myExtension)
'Loop through each Excel file in folder
Set y = Workbooks.Open(destFullpath)
For i = 1 To y.Sheets("Feuil1").Range("M1")
'Ensure Workbook has opened before moving on to next line of code
DoEvents
With y.Sheets("Feuil1").Range("A" & i + 1)
.Formula = "='" & "[" & myFile & "]Para RF'!L2" 'date devis
.Value = .Value
y.Sheets("Feuil1").Range("A" & i + 1).NumberFormat = "dd/mm/yy;#" ' <-- to specify that it is a date format
End With
With y.Sheets("Feuil1").Range("B" & i + 1)
.Formula = "='" & "[" & myFile & "]Para RF'!E11" 'date d'installation
.Value = .Value
End With
With y.Sheets("Feuil1").Range("c" & i + 1)
.Formula = "='" & "[" & myFile & "]Para RF'!H5" 'type
.Value = .Value
End With
With y.Sheets("Feuil1").Range("D" & i + 1)
.Formula = "='" & "[" & myFile & "]Para RF'!H8" 'montant final
.Value = .Value
.NumberFormat = "0.000"
End With
With y.Sheets("Feuil1").Range("E" & i + 1)
.Formula = "='" & "[" & myFile & "]Para RF'!K8" 'montant tarif
.Value = .Value
.NumberFormat = "0.000"
End With
With y.Sheets("Feuil1").Range("F" & i + 1)
.Formula = "='" & "[" & myFile & "]Para RF'!K10" 'remise
.Value = .Value
.NumberFormat = "0.000"
End With
With y.Sheets("Feuil1")
.Range("G2:G" & .Cells(.Rows.count, "F").End(xlUp).Row).Formula = "=$F2/$E2"
y.Sheets("Feuil1").Range("G2:G" & .Cells(.Rows.count, "F").End(xlUp).Row).NumberFormat = "0.00%"
End With
With y.Sheets("Feuil1").Range("H" & i + 1)
.Formula = "='" & "[" & myFile & "]Para RF'!D6" 'société
.Value = .Value
End With
With y.Sheets("Feuil1").Range("I" & i + 1)
.Formula = "='" & "[" & myFile & "]Para RF'!F8" 'ville
.Value = .Value
End With
With y.Sheets("Feuil1").Range("J" & i + 1)
.Formula = "='" & "[" & myFile & "]Para RF'!G5" 'nom vendeur
.Value = .Value
End With
'Ensure Workbook has closed before moving on to next line of code
DoEvents
'Get next file name
myFile = Dir()
Next
'Save and Close Workbook
y.Close saveChanges:=True
'Message Box when tasks are completed
MsgBox "Task Complete!"
ResetSettings:
'Reset Macro Optimization Settings
Application.EnableEvents = True
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub
You're not iterating 50 workbooks. You're iterating 50 file names.
.Formula = "='" & "[" & myFile & "]Para RF'!L2"
Error 1004 on this line means myFile somehow contains invalid characters, or (more likely) that there is no worksheet named Para RF in that workbook.
Try typing ='[that file name.xlsx]Para RF'!L2 directly in a cell (in any workbook). You'll see this:
So, Verify that your formula contains a valid path, workbook, range name, and cell reference.
If there is such a Para RF sheet in the failing workbook, make sure there's no leading/trailing spaces.

Excel Macro to save

I know i should probably be doing this in access or VB but I dont know how to use either. At the moment I have a submit button at the end of my form that saves and closes the workbook as whatever is inputted to a certain cell.
I am looking for a way to be able to do the same thing but break the worksheet out of the workbook. So it saves just the worksheet as its own excel file and with the name inputted into a certain cell. Below is the macro I am currently using.
Sub Saveworkbook()
Application.DisplayAlerts = False
Dim dName$, vName$
dName = Range("B8")
vName = ActiveWorkbook.FullName
ActiveWorkbook.SaveAs "W:\Test\" & dName
ActiveWorkbook.SaveAs vName
ActiveWorkbook.Close
Application.DisplayAlerts = True
End Sub
It would also be cool if it could add the date and computers user in to save name but not essential.
Thanks in advance
Sam
Something like this -
Sub SaveSheet()
Dim wbkDashboard As Workbook
Dim wsTarget As Worksheet
Set wsTarget = Thisworkbook.worksheets("Sheet1")
Dim strFileName As String
strFileName = wsTarget.Range("B8").Value _
& Format(Now, "ddmmyyyy") & "-" & Environ("username") & ".xlsx"
Set wbkDashboard = Workbooks.Add
wsTarget .Copy Before:=wbkDashboard.Sheets(1)
For intSheetCount = 2 To wbkDashboard.Sheets.Count
wbkDashboard.Sheets(2).Delete
Next
wbkDashboard.SaveAs "W:\Test\" & wsTarget.Range("B8").Value _
& Format(Now, "ddmmyyyy") & "-" & Environ("username") & ".xlsx"
wbkDashboard.Close
wsTarget.Range("B8").Value= strFileName
Set wsTarget = Nothing
Set wbkDashboard = Nothing
End Sub
This code will save any changes you have created in the current version, then it will save just the Active Sheet as a new workbook with the username and date (Credit to #Will on the Environment Variables).
Sub Saveworkbook()
Application.DisplayAlerts = False
Dim Sheet1 As Worksheet
Dim dName$, vName$, sName$
dName = Range("B8")
vName = ActiveWorkbook.FullName
sName = ActiveWorkbook.ActiveSheet.Name
For Each Sheet1 In ActiveWorkbook.Sheets
If Not Sheet1.Name = sName Then
Sheet1.Delete
End If
Next Sheet1
ActiveWorkbook.SaveAs "W:\Test\" & dName & "_" & Environ("username") & "_" & Format(Now, "ddmmyy") & "xlsx"
ActiveWorkbook.Close
Application.DisplayAlerts = True
End Sub