Rearranging columns and exIporting range to CSV - vba

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

Related

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

Excel VBA adding data to a chart

Hello I have a little question for adding data to an existing chart.
Now I have a worksheet containing a data series with months for the years in the 2nd row of the sheet. So the months are for example B2 1.2017, C2 2.2017, and in the rows 3,4,5,6,7 and 8 there is always data for that month.
Now I just want my macro to add the new Month plus the data of the rows below to my existing chart.
the code I have so far is this:
Worksheets("Summary").ChartObjects("Chart").Activate
ActiveChart.SeriesCollection.Add _
Source:=Worksheets("Summary").Range("B2:B8")
now this does just create new data series but there is actually no new data added to the chart.
The code below might seem a little long, but it's the safest way to add a new Series with Data to an existing Chart.
I'm setting all the necessary Objects so the code will be as "safe-proof" as can be.
Code
Option Explicit
Sub AddSeriestoChart()
Dim ws As Worksheet
Dim ChtRng As Range
Dim ChtObj As ChartObject
Dim Ser As Series
' set the Worksheet object
Set ws = ThisWorkbook.Worksheets("Summary")
' Set the Chart Object
Set ChtObj = ws.ChartObjects("Chart")
' Set the Range of the Chart's source data
Set ChtRng = ws.Range("B2:B8")
With ChtObj
' add a new series to chart
Set Ser = .Chart.SeriesCollection.NewSeries
' set the source data of the new series
Ser.Values = "=" & ChtRng.Address(False, False, xlA1, xlExternal)
End With
End Sub
Edit 1: to modify existing Series data, use something like the code below :
With ChtObj
For i = 1 To .Chart.SeriesCollection.Count
Set Ser = .Chart.SeriesCollection(i)
' set the source data of the new series
Set ChtRng = ws.Range("B" & i + 2)
Ser.Values = "=" & ChtRng.Address(False, False, xlA1, xlExternal)
Set ChtRng = Nothing
Next i
End With
This is what I would use
wsMetric.ChartObjects("Chart").Chart
'This one will link data from another workbook
.SeriesCollection(1).Values = "='[" & wb.Name & "]" & ws.Name & "'!$" & sCol & "$" & lRow & ":$" & sCol2 & "$" & lRow2
'Debug.Print "='[" & wb.Name & "]" & ws.Name & "'!$" & sCol & "$" & lRow & ":$" & sCol2 & "$" & lRow2 'Returns ='[Book1.xlsm]Sheet1'!$A$1:$A$11
'This one will link data from the same workbook, same or different sheet
.SeriesCollection(1).Values = "=" & ws.Name & "!$" & sCol & "$" & lRow & ":$" & sCol2 & "$" & lRow 2
'Debug.print "=" & ActiveSheet.Name & "!$" & scol & "$" & lrow & ":$" & scol2 & "$" & lrow2 'Returns =Sheet1!$A$1:$A$11
End With
This doesn't use .Activate and directly accesses the chart

Excel VBA: Macro to pull data from files in the folder with skipping already processed ones

I adjusted the code I found on the Internet to pull data from the files in the folder and put them in one master sheet.
However, the numer of files will grow very quickly every week, so for that reason I would like to implement in the code that macro will skip the files that were already processed. I would like to do it by the looking up the file name in the master sheet (column U).
Please find the code below:
Option Explicit
Const FOLDER_PATH = "Z:\...\...\...\" 'REMEMBER END BACKSLASH
Sub ImportWorksheets()
'=============================================
'Process all Excel files in specified folder
'=============================================
Dim sFile As String 'file to process
Dim fName As String
Dim wsTarget As Worksheet
Dim wbSource As Workbook
Dim wsSource As Worksheet
Dim rowTarget As Long 'output row
Dim wsMaster As Worksheet
Dim NR As Long
rowTarget = 3
'Setup
Application.ScreenUpdating = False 'speed up macro execution
Application.EnableEvents = False 'turn off other macros for now
Application.DisplayAlerts = False 'turn off system messages for now
Set wsMaster = ThisWorkbook.Sheets("Arkusz1") 'sheet report is built into
With wsMaster
If MsgBox("Clear the old data first?", vbYesNo) = vbYes Then
.UsedRange.Offset(2).Columns(3).Clear
.UsedRange.Offset(2).Columns(4).Clear
.UsedRange.Offset(2).Columns(5).Clear
.UsedRange.Offset(2).Columns(6).Clear
.UsedRange.Offset(2).Columns(7).Clear
.UsedRange.Offset(2).Columns(8).Clear
.UsedRange.Offset(2).Columns(9).Clear
.UsedRange.Offset(2).Columns(10).Clear
.UsedRange.Offset(2).Columns(11).Clear
.UsedRange.Offset(2).Columns(12).Clear
.UsedRange.Offset(2).Columns(13).Clear
.UsedRange.Offset(2).Columns(14).Clear
.UsedRange.Offset(2).Columns(15).Clear
.UsedRange.Offset(2).Columns(17).Clear
.UsedRange.Offset(2).Columns(18).Clear
.UsedRange.Offset(2).Columns(20).Clear
NR = 3
Else
NR = .Range("A" & .Rows.Count).End(xlUp).Row + 1 'appends data to existing data
End If
'check the folder exists
If Not FileFolderExists(FOLDER_PATH) Then
MsgBox "Specified folder does not exist, exiting!"
Exit Sub
End If
'reset application settings in event of error
On Error GoTo errHandler
Application.ScreenUpdating = False
'set up the target worksheet
Set wsTarget = Sheets("Arkusz1")
'loop through the Excel files in the folder
sFile = Dir(FOLDER_PATH & "*.xls*")
Do Until sFile = ""
'open the source file and set the source worksheet - ASSUMED WORKSHEET(1)
Set wbSource = Workbooks.Open(FOLDER_PATH & sFile)
Set wsSource = wbSource.Worksheets(3) 'EDIT IF NECESSARY
'import the data
With wsTarget
.Range("C" & rowTarget).Value = wsSource.Range("F4").Value
.Range("D" & rowTarget).Value = wsSource.Range("J4").Value
.Range("E" & rowTarget).Value = wsSource.Range("J7").Value
.Range("F" & rowTarget).Value = wsSource.Range("J10").Value
.Range("G" & rowTarget).Value = wsSource.Range("J19").Value
.Range("H" & rowTarget).Value = wsSource.Range("L19").Value
.Range("I" & rowTarget).Value = wsSource.Range("H17").Value
.Range("J" & rowTarget).Value = wsSource.Range("N27").Value
.Range("K" & rowTarget).Value = wsSource.Range("N29").Value
.Range("L" & rowTarget).Value = wsSource.Range("N36").Value
.Range("M" & rowTarget).Value = wsSource.Range("N38").Value
.Range("N" & rowTarget).Value = wsSource.Range("J50").Value
.Range("O" & rowTarget).Value = wsSource.Range("L50").Value
.Range("Q" & rowTarget).Value = wsSource.Range("J52").Value
.Range("R" & rowTarget).Value = wsSource.Range("L52").Value
.Range("T" & rowTarget).Value = wsSource.Range("N57").Value
'optional source filename in the last column
.Range("U" & rowTarget).Value = sFile
End With
'close the source workbook, increment the output row and get the next file
wbSource.Close SaveChanges:=False
rowTarget = rowTarget + 1
sFile = Dir()
Loop
End If
'Format columns to the desired format
.UsedRange.Offset(2).Columns(7).NumberFormat = "### ### ##0"
.UsedRange.Offset(2).Columns(8).NumberFormat = "### ### ##0"
.UsedRange.Offset(2).Columns(9).NumberFormat = "#,##0.00 $"
.UsedRange.Offset(2).Columns(10).NumberFormat = "#,##0.00 $"
.UsedRange.Offset(2).Columns(11).NumberFormat = "#,##0.00 $"
.UsedRange.Offset(2).Columns(12).NumberFormat = "#,##0.00 $"
.UsedRange.Offset(2).Columns(13).NumberFormat = "#,##0.00 $"
.UsedRange.Offset(2).Columns(14).NumberFormat = "0.00%"
.UsedRange.Offset(2).Columns(15).NumberFormat = "0.00%"
.UsedRange.Offset(2).Columns(16).NumberFormat = "0.00%"
.UsedRange.Offset(2).Columns(17).NumberFormat = "0.00%"
.UsedRange.Offset(2).Columns(18).NumberFormat = "0.00%"
.UsedRange.Offset(2).Columns(19).NumberFormat = "0.00%"
.UsedRange.Offset(2).Columns(20).NumberFormat = "0.00%"
errHandler:
On Error Resume Next
Application.ScreenUpdating = True
'tidy up
Set wsSource = Nothing
Set wbSource = Nothing
Set wsTarget = Nothing
End With
End Sub
Private Function FileFolderExists(strPath As String) As Boolean
If Not Dir(strPath, vbDirectory) = vbNullString Then FileFolderExists = True
End Function
I tried to make it by If and GoTo statement but I have very little knowledge in VBA and I have no idea how to actually formulate it skip files which names are already in master sheet.
Thanks in advance!
I'll assume for the moment that the file name in column U is the entire path with file extension. i.e. C:\Users\SL\Desktop\TestFile.xls
You can use the Find method to look for any entries in column U that match sFile at the start of each loop. If a match is found, skip over the file and move on, otherwise process it. Make sure you place sFile = Dir() outside the If statement to avoid an infinite loop.
Dim PathMatch As Range
'loop through the Excel files in the folder
sFile = Dir(FOLDER_PATH & "*.xls*")
Do Until sFile = ""
With wsMaster.Range("U:U")
Set PathMatch = .Find(What:=sFile, _
After:=.Cells(.Cells.Count), _
LookIn:=xlValues, _
LookAt:=xlWhole, _
SearchOrder:=xlByRows, _
SearchDirection:=xlNext, _
MatchCase:=False)
End With
If Not PathMatch Is Nothing Then
Debug.Print "File already processed, skip to next file."
Else
Debug.Print "File not processed yet, do it now"
'open the source file and set the source worksheet - ASSUMED WORKSHEET(1)
Set wbSource = Workbooks.Open(FOLDER_PATH & sFile)
Set wsSource = wbSource.Worksheets(3) 'EDIT IF NECESSARY
'import the data
With wsTarget
.Range("C" & rowTarget).Value = wsSource.Range("F4").Value
.Range("D" & rowTarget).Value = wsSource.Range("J4").Value
.Range("E" & rowTarget).Value = wsSource.Range("J7").Value
.Range("F" & rowTarget).Value = wsSource.Range("J10").Value
.Range("G" & rowTarget).Value = wsSource.Range("J19").Value
.Range("H" & rowTarget).Value = wsSource.Range("L19").Value
.Range("I" & rowTarget).Value = wsSource.Range("H17").Value
.Range("J" & rowTarget).Value = wsSource.Range("N27").Value
.Range("K" & rowTarget).Value = wsSource.Range("N29").Value
.Range("L" & rowTarget).Value = wsSource.Range("N36").Value
.Range("M" & rowTarget).Value = wsSource.Range("N38").Value
.Range("N" & rowTarget).Value = wsSource.Range("J50").Value
.Range("O" & rowTarget).Value = wsSource.Range("L50").Value
.Range("Q" & rowTarget).Value = wsSource.Range("J52").Value
.Range("R" & rowTarget).Value = wsSource.Range("L52").Value
.Range("T" & rowTarget).Value = wsSource.Range("N57").Value
'optional source filename in the last column
.Range("U" & rowTarget).Value = sFile
End With
'close the source workbook, increment the output row and get the next file
wbSource.Close SaveChanges:=False
rowTarget = rowTarget + 1
End If
sFile = Dir()
Loop
If you only have the file name and not the path you'll need to parse sFile accordingly. Here are a few ways to do that.

Macro to Copy Row if Highlighted and Concatenate

I have an Excel sheet with data I would like to concatenate and use to create an .ini file.
There are multiple columns with data, if a cell in column D is highlighted I want it to copy the data in that row on to another sheet but at the same time I want it to concatenate the data in each column with the column header, see below:
From the picture above I would like the macro to copy the data into another sheet in the following format:
name = Machine 1
caption = Presentation
make = Company 1
model = Model 1
Is this possible?
If you want to create a ini file and not a sheet with ini look. Use this code:
LastRow = Range("A" & Rows.Count).End(xlUp).Row
for i = 3 to LastRow
If range("A" & i).Interior.ColorIndex = 2 then
MyFile = "C:\inifiles\" & Range("C" & i).Value & ".ini" 'Machine 1.ini
fnum = FreeFile()
Open MyFile For Output As #fnum
Print #fnum, "name=" & Range("C" & i).Value
Print #fnum, "caption=" & Range("D" & i).Value
Print #fnum, "make=" & Range("E" & i).Value
Print #fnum, "model=" & Range("F" & i).Value
Close #fnum
End if
Next i
It loops through all rows and uses the data to create a file with the "name" as the name of the file.
EDIT:
If you want to create the sheets with ini look:
LastRow = Range("A" & Rows.Count).End(xlUp).Row
For i = 3 To LastRow
If range("A" & i).Interior.ColorIndex = 2 then
Dim ws As Worksheet
Set ws = ThisWorkbook.Sheets.Add(After:= _
ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count))
ws.Name = Sheets(1).Range("C" & i).Value
Sheets(Sheets(1).Range("C" & i).Value).Range("A1") = "name=" & Sheets(1).Range("C" & i).Value
Sheets(Sheets(1).Range("C" & i).Value).Range("A2") = "caption=" & Sheets(1).Range("D" & i).Value
Sheets(Sheets(1).Range("C" & i).Value).Range("A3") = "make=" & Sheets(1).Range("E" & i).Value
Sheets(Sheets(1).Range("C" & i).Value).Range("A4") = "model=" & Sheets(1).Range("F" & i).Value
End if
Next i

Loop and set value for coulmns

I am currently using the set value method to copy data from multiple workbooks. I can currently loop through all workbooks and set the values from one sheet, worksheet2(Title) as seen below, and copy them to "thisWorkbook" on "sheet1", my destination. How can I loop through worksheets 3 to 9 and copy the range A2:C57 into columns G,H,I using the same set value method?
Sub GetData()
Dim MyPath As String
Dim FileName As String
Dim SheetName As String
Dim NewRow As Long
MyPath = "C:\attach"
SheetName = "Title"
FileName = Dir(MyPath & "\*.xlsx")
Do While FileName <> ""
If FileName <> ThisWorkbook.Name Then
With ThisWorkbook.Sheets("Sheet1")
NewRow = .Cells(Rows.Count, 1).End(xlUp).Row + 1
With .Range("A" & NewRow)
.Formula = "='" & MyPath & "\[" & FileName & "]" & SheetName & "'!B4"
.Value = .Value
End With
With .Range("B" & NewRow)
.Formula = "='" & MyPath & "\[" & FileName & "]" & SheetName & "'!B5"
.Value = .Value
End With
With .Range("C" & NewRow)
.Formula = "='" & MyPath & "\[" & FileName & "]" & SheetName & "'!B6"
.Value = .Value
End With
With .Range("D" & NewRow)
.Formula = "='" & MyPath & "\[" & FileName & "]" & SheetName & "'!B7"
.Value = .Value
End With
With .Range("E" & NewRow)
.Formula = "='" & MyPath & "\[" & FileName & "]" & SheetName & "'!A1"
.Value = .Value
End With
With .Range("F" & NewRow)
.Formula = "='" & MyPath & "\[" & FileName & "]" & SheetName & "'!A2"
.Value = .Value
End With
'Copy the range A2:C57 from workheets (3 to 9) and past into columns G,H,I in thisworkbook from every workbook in folder.
'For sheets 3 to 9 set the value range A2:C57 to G,H,I in thisworkbook. This would be done for every workbook in the folder
End With
End If
FileName = Dir
Loop
ThisWorkbook.Sheets("Sheet1").Columns.AutoFit
End Sub
I'm not entirely sure if this is what you're asking, but I think the range.copy is what you want.
To get the entire worksheet 3-9 you can use
' A2:C57 = Cells (2,1),Cells(57,3)
For Sheetindex= 3 to ThisWorkbook.Worksheets.Count
'Copy Worksheet 3 A2:C57
Set SourceRange = ThisWorkbook.WorkSheets(Sheetindex).Range(Cells(2,1),Cells(57,3))
' Paste it in Columns G,H,I starting in Row 1.
SourceRange.Copy (ThisWorkbook.Worksheets("Sheet1").Cells("G1"))
Next Sheetindex