Automation 31 templates or 1 template - sql

am producing an excel report where I bring in data for one country via a data connection and then run a macro that refesh pivots and other sheets with that data and then closes and saves the Excel report for that country. For example Germany . I have then another 31 templates for other countries where the same process happens. The differences between the 31 templates is that the database sql query for the data connection ( bring records for Germany ) and the filename that it is saved as like Report_Germany .
In SSIS, I am using a process task that calls a vbs script which simply opens an excel file and runs a macros for each country . Now I do not want to create 31 different SSIS tasks.
Anyway I could use 1 Template and produce the required 31 Excel Reports in the same directory ?

Yes, it is possible to use a single temple to create multiple reports.
All your pivot tables need to have a report filter equal to the country and all the data needs to be retrieved into one workbook.
Then you can loop through the countries setting the filters each time and saving the workbook as with a separate country name.
Listed below is some basic code to achieve this.
Sub Update_Pivot_filter()
Dim StaticArray(1 To 3) As String
Dim strName As String
Dim lCount As Long
StaticArray(1) = "Germany"
StaticArray(2) = "France"
StaticArray(3) = "Italy"
For lCount = LBound(StaticArray) To UBound(StaticArray)
ActiveWorkbook.Sheets("Sheet1").PivotTables("PivotTable1"). _
PivotFields("Name").CurrentPage = StaticArray(lCount)
' Change report filter on a pivot table
ActiveWorkbook.RefreshAll
' Refresh all pivot tables
ActiveWorkbook.SaveAs Filename:= _
"C:\Temp\Report_" & StaticArray(lCount) & ".xlsx", _
FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False
' Save the file with a name matching the filter name
MsgBox StaticArray(lCount)
Next lCount
End Sub
The downside of this approach is that each workbook contains all your data.

Related

Importing Data from Excel file to MSAccess formatting each column in VBA

I'm coding a system which import a excel file to a ms access database, but I would like to know if is possible format every column before import to the database.
For example:
EXCEL FILE (xls or xlsx): COLUMN A = DateTime; COLUMN B = Integer; COLUMN C = Char(25); COLUMN D = VARCHAR(255)...
I'm using this code right now but it's automatically.
Do While Len(strFile) > 0
strPathFile = strPath & strFile
DoCmd.TransferSpreadsheet acImport, acSpreadsheetTypeExcel9, _
strTable, strPathFile, blnHasFieldNames
strFile = Dir()
Loop
Yes it is possible and advisable to format the columns in excel before importing, so as to reduce risk of some data not been correctly imported.
Select the cells(s) you want to modify.
Click the drop-down arrow next to the Number Format command on the Home tab. The Number Formatting drop-down menu will appear.
Select the desired formatting option
formatting options in excel includes
A.ABC General
B. Number
C Currency
D Short date
E Long date
and some others.
You have to format the columns in excel manually, it can not be programmatically done from access

segregate the data based on their own value

I have data where list is dynamic. I would like to segregate the data base on their own value.I am unable to predict the exact value coming every time. Example : - This time I got company code as 1959809 and 1960574. I would like to filter data based on company code and would like to paste it in new workbook. This number will get change every time. Next time the company code may be 1960574 and 1963665.
I am thinking that we need to group the company code value so that we can have it in variable. However, I am unable to get the logic.
I am not getting any logic to do so. Hence, I don't have anything to show.
We should get two or more workbooks based on company code along with respective data.
Assuming your data has first column as 'Company Code' and starts from the first row of sheet, Following code will help you achieving your goal:
Sub ExportFilteredData()
Dim Codes As String, CodesArray, Code
Dim Wb As Workbook, CurSht As Worksheet
'Get the company codes from user as comma separated values
Codes = InputBox("Enter Company codes separated by comma")
CodesArray = Split(Codes, ",") 'Split company codes to array
'Save the data sheet reference and remove any applied filter
Set CurSht = ActiveSheet
CurSht.AutoFilterMode = False
'Filter data for each company code and save as new workbook
For Each Code In CodesArray
'Change the 'Field' value to the actual 'Company Code' column number
CurSht.Range("A1").AutoFilter Field:=1, Criteria1:=Trim(Code)
Set Wb = Workbooks.Add
CurSht.AutoFilter.Range.SpecialCells(xlCellTypeVisible).Copy Wb.Sheets(1).Range("A1")
'Change the path and filename as per your requirement
Wb.SaveAs ThisWorkbook.Path & "\" & Trim(Code) & ".xlsx"
Wb.Close False
CurSht.AutoFilterMode = False
Next
End Sub

Excel VBA to filter Pivot Table and Pivot Chart for previous day - Pivot Filter Field

Here is my problem, every bit of code, every alteration, every type, doesn't work. I'm using Office 360 at my work site (up to date), so it's excel 2016 and VBA 7.1.
What I'm looking to do is automate our end of shift reports. Here's the process:
We enter data into an excel sheet (Log) every hour. At the end of the day, at 5:00 AM, we save and close that log, open another excel sheet that IMPORTS the data into power pivot, and displays it on a PivotTable (formatting for printing for our bosses), and we choose the filter for the previous date using the filter drop down, and print it. We do this with three (3) reports: 2 PivotTables, and 1 PivotChart. Power Pivot imports ALL of the data from the Log sheet to reformat it for printing.
I've successfully managed to get and rewrite the code (beginner at this) for the automation process of: auto saving the log, closing the log, opening the Report workbook, refreshing the data, and printing the data, then closing the report. The only part I'm now missing is the auto-filtering.
The code I've tried is vast, but here's an example of what I've tried recently (I've erased and re-copied so many codes...)
Sub Filter_PivotField()
'Description: Filter a pivot table or slicer for a specific date or period
'Source: excelcampus.com/vba/filter-pivot-table-slicer-recent-date-period
Dim sSheetName As String
Dim sPivotName As String
Dim sFieldName As String
Dim sFilterCrit As String
Dim pi As PivotFields
'Set the variables
sSheetName = "EOS Report"
sPivotName = "PivotTable1"
sFieldName = "Date"
sFilterCrit = "xlDateYesterday"
'sFilterCrit = ThisWorkbook.Worksheets("EOS Report").Range("O1").Value
With ThisWorkbook.Worksheets(sSheetName).PivotTables(sPivotName).PivotFields(sFieldName)
'Clear all filter of the pivotfield
.ClearAllFilters
'Loop through pivot items of the pivot field
'Hide or filter out items that do not match the criteria
For Each pi In .PivotFields
If pi.Name <> sFilterCrit Then
pi.Visible = False
End If
Next pi
End With
End Sub
To no avail....
When I record a macro doing the manual filter, I get this:
Sub manualfilter()
'
' manualfilter Macro
'
'
ActiveSheet.PivotTables("PivotTable1").PivotFields( _
"[Bi-Hourly Report].[Date].[Date]").VisibleItemsList = Array( _
"[Bi-Hourly Report].[Date].&[2016-09-28T00:00:00]")
End Sub
But it fails when I try to re-run the same macro that I just recorded (after changing the date back). I've enabled and disabled multiple selection option, etc.
Not to mention, trying to auto-filter a chart is a nightmare because tables, yea there's tons of articles on it, but charts? not much comes up on researching.
Here's images of the filter button, because almost everything I've researched is to sort the COLUMN of the Table, not the filter itself with a PivotTable.
Table Filter
Chart Filter
I cannot post the actual excel spreadsheets as they are proprietary property of the company, but I can replicate the format with false data if needed.
check this out.
Dim prev_date As String
prev_date = Month(Date - 1) & "/" & Day(Date - 1) & "/" & Year(Date - 1)
Thisworkbook.Sheets("Sheet1").Activate
'change this line with your sheet where pivot table is present. Change Sheet name.
ActiveSheet.PivotTables("PivotTable1").RefreshTable
ActiveSheet.PivotTables("PivotTable1").PivotFields("Date").CurrentPage = prev_date

Merge tables from many separate workbooks

I want to merge specific contents of 2713 workbooks into a single worksheet. Lets say the individual files contain sales revenues for different sales outlets.
Each of the workbooks uses only 1 worksheet. Each of those worksheets contains one or more tables in identical format. Worksheets contain no fuctions whatsoever. This sample shows cells A1:E7
A1 contains the number of the specific outlet
A2 contains the reference date, e.g. 31.12.2014
A3:E3 contain the column headers: No.; Item; Revenue current period; Revenue previous period
A4:E10 contain the info I want transported to the new single file
A11:E11 contains the total amounts
Row 12 is blank
Another table with info for 31.12.2013 starts from row 13.
...
Most of the worksheets have more than just one table. All of them start like the one above. The tables have identical layout.
Unfortunately, the number of products varies a lot (1-250). For the example, I just assumed its 7 products. I don't need the row for headline or total.
How can I get those rows into a new single worksheet?
The outlet number in cell A1 on every sheet should be added in the cell to the right of the cells containing comment.
I want to avoid having to open the 2713 files one after the other in order to copy and paste the info in 2713 drag and drop moves into a merged worksheet.
I hope you can help or its gonna be a long weekend.
Best wishes,
Peter
I'm assuming here that when you say tables you mean defined tables of data.
The code below assumes that all tables are the same size (target and source tables).
There's no error checking and minimal testing - so check on some test workbooks first.
Sub GetTables()
Dim colWrkBks As Collection 'Contains path to all workbooks.
Dim vPath As Variant 'Current workbook path.
Dim wrkBk As Workbook 'Current workbook.
Dim wrksht As Worksheet 'Worksheet within wrkBk.
Dim oListObject As Object 'Tables within wrksht.
Dim oTargetTable As Object 'The table to hold all the data.
Dim sTmp As String
Dim sDirectory As String
'Make sure you have a table defined to place all the data in.
'Update worksheet and table name as required.
Set oTargetTable = ThisWorkbook.Worksheets("Sheet1").ListObjects("Table1")
'Get full path of all workbooks in source folder.
'*Update directory and file extension as required
Set colWrkBks = New Collection
sDirectory = "C:\Users\Darren\Documents\Work\New folder\"
sTemp = Dir$(sDirectory & "*.xls*")
Do While Len(sTemp) > 0
colWrkBks.Add sDirectory & sTemp
sTemp = Dir$
Loop
'Open each workbook and copy the data from source table to target table.
For Each vPath In colWrkBks
Set wrkBk = Workbooks.Open(vPath, False)
'1 references the first worksheet - you can use "Sheet1" for a specific sheet name.
Set wrksht = wrkBk.Worksheets(1)
'Cycle through each table in the worksheet.
For Each oListObject In wrksht.ListObjects
oTargetTable.ListRows.Add
oListObject.DataBodyRange.Rows("1:" & oListObject.DataBodyRange.Rows.Count).Copy _
oTargetTable.DataBodyRange.Rows(oTargetTable.DataBodyRange.Rows.Count)
Next oListObject
wrkBk.Close False
Next vPath
End Sub

Ctrl+A, format as table

I have a 3000 rows by 50 columns dataset in Excel starting in A1.
I recorded and edited a macro that emulates the following: Ctrl+A, Format as table:
Dim koosrange As Range
Set koosrange = ActiveSheet.UsedRange
koosrange.Select
ActiveSheet.QueryTables("aspectsClean_1").Delete
ActiveSheet.QueryTables("aspectsClean").Delete
ActiveSheet.ListObjects.Add(xlSrcRange, koosrange, , xlNo).Name = _
"Table1"
Range("Table1[#All]").Select
ActiveSheet.ListObjects("Table1").TableStyle = "TableStyleLight1"
ActiveSheet.ListObjects("Table1").ShowTableStyleFirstColumn = True
The entire program consists of 3 parts:
Import data from *.txt
Concatenate item names to only fit in Col A, and move all other data left, to start in Col B
Format all data as table (so that it can be filtered, etc.)
When running the program, the following error occurs on ActiveSheet.ListObjects.Add(xlSrcRange, koosrange, , xlNo).Name = _
"Table1" (line 6 of the previous code excerpt):
Error: A table cannot overlap a range that contains a PivotTable report, query results, protected cells or another table
Further to my comment, if you used the recorder to record Import > From Text File then the method it would be using would be to add a querytable object connected to the text file, then refreshing it.
Depending on some of the circumstances - I am not fully familiar with the different objects at play in this situation - it is necessary to delete, if they were created, both the connection object and the querytable object.
E.g. a recording i did just now churned out:
With ActiveSheet.QueryTables.Add(Connection:= _
"TEXT;{snipped path}", Destination:=Range("$A$1"))
.Name = "new 2"
'+some other properties churned out removed here for conciseness
.Refresh BackgroundQuery:=False
End With
So, add just before the End With:
If Not ActiveWorkbook.Connections(.Name) Is Nothing Then
ActiveWorkbook.Connections(.Name).Delete
End If
.Delete
End With