**I m trying to create three different sheets with this Macro code. So when i run this code those the sheets are creating as it should, but i want to rename these sheets created with particular name and delete them or replace them when i run the code again.
So the below code is the modified in such a way that it creates 2 pivot sheet and one sheet with data that creates the count of range defined... with countifs
SO when i searched the internet for an alternative i tried the other code but the but the range(dynamic) is not getting selected while creating pivot table. it throws an error
SetwsPT=wb.Worksheets.Add
Please help.
Sub MacroPivotReceivedResolved()
Sheets.Add
pivotWS = ActiveSheet.Name
ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
"ReceivedMacro!R6C1:R20000C54", Version:=xlPivotTableVersion15). _
CreatePivotTable TableDestination:=pivotWS & "!R3C1", TableName:="PivotTable5" _
, DefaultVersion:=xlPivotTableVersion15
Sheets(pivotWS).Select
Cells(3, 3).Select
ActiveSheet.PivotTables("PivotTable5").RowAxisLayout xlTabularRow
With ActiveSheet.PivotTables("PivotTable5").PivotFields("Receipt Date")
.Orientation = xlRowField
.Position = 1
End With
ActiveSheet.PivotTables("PivotTable5").AddDataField ActiveSheet.PivotTables( _
"PivotTable5").PivotFields("Receipt Date"), "Count of Case Age", xlCount
Sheets("ResolvedMacro").Select
Range("A6").Select
Sheets.Add
pivotWS1 = ActiveSheet.Name
ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
"ResolvedMacro!R6C1:R20000C54", Version:=xlPivotTableVersion15). _
CreatePivotTable TableDestination:=pivotWS1 & "!R3C1", TableName:="PivotTable6" _
, DefaultVersion:=xlPivotTableVersion15
Sheets(pivotWS1).Select
Cells(3, 3).Select
With ActiveSheet.PivotTables("PivotTable6").PivotFields("Resolved Date")
.Orientation = xlRowField
.Position = 1
End With
ActiveSheet.PivotTables("PivotTable6").AddDataField ActiveSheet.PivotTables( _
"PivotTable6").PivotFields("Resolved Date"), "Count of Case Age", xlCount
Sheets("ReceivedMacroAge").Select
Range("A6").Select
Range(Selection, Selection.End(xlToRight)).Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Copy
Sheets.Add After:=ActiveSheet
Range("A1").Select
ActiveSheet.Paste
Application.CutCopyMode = False
With Selection
.VerticalAlignment = xlTop
.WrapText = False
.Orientation = 0
.AddIndent = False
.IndentLevel = 0
.ShrinkToFit = False
.ReadingOrder = xlLTR
.MergeCells = False
End With
Columns("A:A").ColumnWidth = 16.29
Cells.Select
Selection.ColumnWidth = 17.57
Columns("J:J").Select
Selection.Insert Shift:=xlToRight
Range("J2").Select
ActiveCell.FormulaR1C1 = "=COUNT"
Columns("J:J").Select
Selection.Delete Shift:=xlToLeft
Rows("1:1").Select
Selection.Insert Shift:=xlDown
Selection.Insert Shift:=xlDown
Selection.Insert Shift:=xlDown
Selection.Insert Shift:=xlDown
Selection.Insert Shift:=xlDown
Selection.Insert Shift:=xlDown
Selection.Insert Shift:=xlDown
Selection.Insert Shift:=xlDown
Selection.Insert Shift:=xlDown
Range("H1").Select
ActiveCell.FormulaR1C1 = "Total Outstanding"
Range("I1").Select
ActiveCell.FormulaR1C1 = "=SUM(R[1]C:R[5]C)"
Range("H2").Select
ActiveCell.FormulaR1C1 = "Over 8 Weeks (Over 56 Days)"
Range("I2").Select
ActiveCell.FormulaR1C1 = "=COUNTIFS(R[9]C:R[1000]C, "">=57"")"
Range("H3").Select
ActiveCell.FormulaR1C1 = "6-8 Weeks (42-56 days)"
Range("I3").Select
ActiveCell.FormulaR1C1 = _
"=SUMPRODUCT(INT(R[9]C:R[1000]C>=42), INT(R[9]C:R[1000]C<57))"
Range("H4").Select
ActiveCell.FormulaR1C1 = "4-6 weeks (28 - 41)"
Range("I4").Select
ActiveCell.FormulaR1C1 = _
"=SUMPRODUCT(INT(R[9]C:R[1000]C>=28), INT(R[9]C:R[1000]C<42))"
Range("H5").Select
ActiveCell.FormulaR1C1 = "2-4 Weeks (14 - 27)"
Range("I5").Select
ActiveCell.FormulaR1C1 = _
"=SUMPRODUCT(INT(R[9]C:R[1000]C>=14), INT(R[9]C:R[1000]C<28))"
Range("H6").Select
ActiveCell.FormulaR1C1 = "0-2 Weeks (0-13)"
Range("I6").Select
ActiveCell.FormulaR1C1 = _
"=SUMPRODUCT(INT(R[9]C:R[1000]C>=1), INT(R[9]C:R[1000]C<14))"
Range("H7").Select
ActiveCell.FormulaR1C1 = "Cases to breach next day ( Day 56)"
Range("I7").Select
ActiveCell.FormulaR1C1 = "=COUNTIFS(R[9]C:R[1000]C, ""=56"")"
Range("H8").Select
End Sub
Here's a basic example of how to remove and replace a worksheet:
Sub MacroPivotReceivedResolved()
Const PIVOTA_NAME As String = "Pivot A"
Dim wsPivot As Worksheet, wb As Workbook, pc As PivotCache, pt As PivotTable
Set wb = ThisWorkbook 'for example
DeleteSheet wb, PIVOTA_NAME 'delete the sheet if it exists
Set wsPivot = wb.Sheets.Add 'add new sheet for pivot table
wsPivot.Name = PIVOTA_NAME
'create the pivot cache
Set pc = wb.PivotCaches.Create(SourceType:=xlDatabase, _
SourceData:="ReceivedMacro!R6C1:R20000C54", _
Version:=xlPivotTableVersion15)
'create the pivot table
Set pt = pc.CreatePivotTable(TableDestination:=pivotWS.Range("A3"), _
TableName:="PivotTable5", _
DefaultVersion:=xlPivotTableVersion15)
'now you can use `pt` instead of `ActiveSheet.PivotTables("PivotTable5")`
pt.RowAxisLayout xlTabularRow
With pt.PivotFields("Receipt Date")
.Orientation = xlRowField
.Position = 1
End With
pt.AddDataField pt.PivotFields("Receipt Date"), "Count of Case Age", xlCount
End Sub
'Remove any worksheet named `wsName` from workbook `wb`,
' ignoring any error if no sheet with that name is found
Sub DeleteSheet(wb As Workbook, wsName As String)
Dim ws As Worksheet, da As Boolean
On Error Resume Next 'ignore error if sheet doesn't exist
Set ws = wb.Worksheets(wsName)
On Error GoTo 0 'stop ignoring errors
If Not ws Is Nothing Then
da = Application.DisplayAlerts 'get current setting
Application.DisplayAlerts = False 'turn off alerts
wb.Worksheets(wsName).Delete
Application.DisplayAlerts = da 'restore previous setting
End If
End Sub
Related
I have this code so far and at the end of this code I need to identify the memberID which is a combination of the ParticipantID with a concatenate _1, _2, _3, _4, _5, 6… etc.… In order to determine the '#' assignment I have identified the ‘Participant ID Count’ that the Member has. What I am or have been attempting to do is paste the concatenate in the filtered range for the column specified. For example When filtered on Member Num Count = 5:
Participant ID Member Num Count Concate
002162 5 002162_1
002162 5 002162_2
002162 5 002162_3
002162 5 002162_4
002162 5 002162_5
002210 5 002210_1
002210 5 002210_2
002210 5 002210_3
002210 5 002210_4
002210 5 002210_5
I feel like I’m very close to completing thing this, I’m just missing something.
Sub CreatePivotTable()
Dim PTCache As PivotCache
Dim pt As Variant
Dim WS As Worksheet
On Error Resume Next
Application.DisplayAlerts = False
Sheets("Pivot").Delete
On Error GoTo 0
With Workbooks("Formatting.xlsm").Sheets("Dependants")
.Range("A1").End(xlToRight).Offset(, 1).Value = "Count"
.Range("A1").End(xlToRight).Offset(, 1).Value = "DependantID"
.Range("A1").EntireColumn.Insert (xlShiftToLeft)
.Range("A1").Value = "Concate"
.Cells.AutoFilter
.Range("B1").End(xlDown).Offset(0, -1).Activate
ActiveCell.FormulaR1C1 = "=CONCAT(RC[1],""|"",RC[10])"
With ActiveCell
.Copy
.End(xlUp).Offset(1, 0).Select
End With
Range(Selection, Selection.End(xlDown)).Select
ActiveSheet.Paste
.Range("B1").EntireColumn.NumberFormat = "000000"
ActiveCell.EntireColumn.Copy
End With
With Workbooks("Formatting.xlsm")
.Sheets.Add After:=ActiveSheet
.ActiveSheet.Name = "Working"
.ActiveSheet.Range("A1").PasteSpecial Paste:=xlPasteValues
Sheets("Working").Columns("A:A").Activate
ActiveSheet.Range("A:A").RemoveDuplicates Columns:=1, Header:=xlNo
End With
Columns("A:A").TextToColumns Destination:=Range("A1"), DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=False, _
Semicolon:=False, Comma:=False, Space:=False, Other:=True, OtherChar _
:="|", FieldInfo:=Array(Array(1, 1), Array(2, 1)), TrailingMinusNumbers:=True
With Worksheets("Working")
.Range("B1").Value = "Dependent Num"
.Range("A1").Value = "Participant ID"
End With
Set PTCache = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, _
SourceData:=Sheets("Working").Range("A1").CurrentRegion)
Worksheets.Add
ActiveSheet.Name = "Pivot"
Set pt = ActiveSheet.PivotTables.Add(PivotCache:=PTCache, TableDestination:=Range("A3"))
With pt
.PivotFields("Participant ID").Orientation = xlRowField
.PivotFields("Dependent Num").Orientation = xlDataField
.RowGrand = False
.ColumnGrand = False
Subtotals = False
End With
Range("B3").Select
With ActiveSheet.PivotTables(1).PivotFields("Sum of Dependent Num")
.Caption = "Count of Dependent Num"
.Function = xlCount
End With
With Worksheets("Pivot")
.Range("A3").CurrentRegion.Copy
.Range("E3").PasteSpecial Paste:=xlPasteValues
.Range("E:E").NumberFormat = "000000"
End With
Worksheets("Dependants").Activate
Range("A1").End(xlToRight).Offset(1, 0).Activate
ActiveCell.FormulaR1C1 = "=VLOOKUP(RC[-18],Pivot!C4:C5,2,)"
Range("S1").End(xlDown).Offset(, 1).Activate
With ActiveCell
.FormulaR1C1 = "=VLOOKUP(RC[-18],Pivot!C5:C6,2,)"
.Copy
.End(xlUp).Offset(1, 0).Select
End With
Range(Selection, Selection.End(xlDown)).Select
ActiveSheet.Paste
Range("T:T").Copy
Range("T:T").PasteSpecial Paste:=xlPasteValues
Sheets("Pivot").Activate
Range("B3").Activate
Dim pf As PivotField
On Error Resume Next
For Each pt In ActiveSheet.PivotTables
For Each pf In pt.PivotFields
'First, set index 1 (Automatic) to True,
'so all other values are set to False
pf.Subtotals(1) = True
pf.Subtotals(1) = False
Next pf
Next pt
Set pvttbl = ActiveSheet.PivotTables(1)
With ActiveSheet.PivotTables(1)
On Error Resume Next
.PivotFields("Count of Dependent Num").Orientation = xlHidden
On Error GoTo 0
.PivotFields("Dependent Num").Orientation = xlRowField
.RowAxisLayout xlTabularRow
.RepeatAllLabels xlRepeatLabels
.ColumnGrand = False
.RowGrand = False
End With
Sheets("Pivot").Activate
Range("A3").CurrentRegion.Copy
Range("H3").PasteSpecial Paste:=xlPasteValues
Range("H:H").NumberFormat = "000000"
Range("H3").End(xlToRight).Offset(0, 1).Value = "Dependent Count"
Range("J4").Activate
ActiveCell.FormulaR1C1 = "=VLOOKUP(RC[-2],C5:C6,2,)"
ActiveCell.Copy
Range("I3").End(xlDown).Offset(0, 1).Activate
Range(Selection, Selection.End(xlUp)).Offset(1, 0).Select
ActiveSheet
'ActiveSheet.Range("H:K").AutoFilter Field:=2, Criteria1:="0"
'Range("I3").End(xlDown).Select
'Range(Selection, Selection.End(xlUp)).Offset(1, 0).ClearContents
'ActiveSheet.Range("H3:K3").AutoFilter
'ActiveSheet.Range("H3:K3").AutoFilter
With ActiveSheet.Range("H3").CurrentRegion
.AutoFilter Field:=3, Criteria1:="1"
If .Columns(1).SpecialCells(xlCellTypeVisible).Count > 1 Then
With .Columns(4)
.Resize(.Rows.Count - 1).Offset(1).SpecialCells(xlCellTypeVisible).FormulaR1C1 = "=CONCAT(""00"",RC[-3],""_1"")"
End With
End If
End With
'Create DependentIDs
Set WS = Worksheets("Pivot")
WS.Range("H:K").AutoFilter Field:=3, Criteria1:="2"
WS.Range("J3").End(xlDown).Offset(0, 1).Activate
ActiveCell.FormulaR1C1 = "=CONCAT(""00"",RC[-3],""_2"")"
WS.Range("K3").End(xlDown).Offset(-1, 0).Activate
ActiveCell.FormulaR1C1 = "=CONCAT(""00"",RC[-3],""_1"")"
Range(Selection, Selection.End(xlDown)).Copy
WS.Range(Selection, Selection.End(xlUp)).SpecialCells(xlCellTypeVisible).Offset(2, 0).Activate
WS.Paste
WS.Range("J3").End(xlDown).Offset(0, 1).Activate
ActiveCell.End(xlUp).Offset(-2, 0).Activate
WS.Paste
'This is where my code fails. I'm trying to paste the formula in the cells with the filter of 3. As mentioned before, I need to have 1 through the number of member count exists for each member.
WS.Range("H:K").AutoFilter Field:=3, Criteria1:="3"
WS.Range("J3").End(xlDown).Offset(0, 1).Activate
ActiveCell.FormulaR1C1 = "=CONCAT(""00"",RC[-3],""_3"")"
WS.Range("K3").End(xlDown).Offset(-1, 0).Activate
ActiveCell.FormulaR1C1 = "=CONCAT(""00"",RC[-3],""_2"")"
WS.Range("K3").End(xlDown).Offset(-1, 0).Activate
ActiveCell.FormulaR1C1 = "=CONCAT(""00"",RC[-3],""_1"")"
Range(Selection, Selection.End(xlDown)).Copy
WS.Range(Selection, Selection.End(xlUp)).SpecialCells(xlCellTypeVisible).Offset(3, 0).Activate
WS.Paste
End Sub
I want to create 14 pivot table.I have recorded a macro.My macro code is given below.If I want to apply for loop to create 14 pivot tables, how to do that?
I am a beginner so unable to understand how to apply for loop to automate this recorded code?
My macro is given below:
Sub Macro1()
'
' Macro1 Macro
'
'
Range("A1").Select
Range(Selection, Selection.End(xlToRight)).Select
Range(Selection, Selection.End(xlToRight)).Select
Range(Selection, Selection.End(xlToLeft)).Select
Range(Selection, Selection.End(xlDown)).Select
Range(Selection, Selection.End(xlDown)).Select
Range(Selection, Selection.End(xlDown)).Select
Range(Selection, Selection.End(xlDown)).Select
Sheets.Add
ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
"Current Fleet Comparison!R1C1:R1048576C41", Version:=xlPivotTableVersion14). _
CreatePivotTable TableDestination:="Sheet1!R3C1", TableName:="PivotTable1" _
, DefaultVersion:=xlPivotTableVersion14
Sheets("Sheet1").Select
Cells(3, 1).Select
ActiveWorkbook.ShowPivotTableFieldList = True
With ActiveSheet.PivotTables("PivotTable1").PivotFields("AircraftType")
.Orientation = xlPageField
.Position = 1
End With
ActiveSheet.PivotTables("PivotTable1").AddDataField ActiveSheet.PivotTables( _
"PivotTable1").PivotFields("AircraftType"), "Count of AircraftType", xlCount
With ActiveSheet.PivotTables("PivotTable1").PivotFields("OperatorArea")
.Orientation = xlColumnField
.Position = 1
End With
Range("A1:F5").Select
Selection.Copy
Range("A8").Select
ActiveSheet.Paste
ActiveSheet.PivotTables("PivotTable2").PivotFields("AircraftType"). _
ClearAllFilters
ActiveSheet.PivotTables("PivotTable2").PivotFields("AircraftType").CurrentPage _
= "A318"
Range("A15").Select
ActiveSheet.Paste
ActiveSheet.PivotTables("PivotTable3").PivotFields("AircraftType"). _
ClearAllFilters
ActiveSheet.PivotTables("PivotTable3").PivotFields("AircraftType").CurrentPage _
= "A319"
Range("A22").Select
ActiveSheet.Paste
ActiveSheet.PivotTables("PivotTable4").PivotFields("AircraftType"). _
ClearAllFilters
ActiveSheet.PivotTables("PivotTable4").PivotFields("AircraftType").CurrentPage _
= "A320"
ActiveWindow.SmallScroll Down:=15
Range("A29").Select
ActiveSheet.Paste
ActiveSheet.PivotTables("PivotTable5").PivotFields("AircraftType"). _
ClearAllFilters
ActiveSheet.PivotTables("PivotTable5").PivotFields("AircraftType").CurrentPage _
= "A321"
Range("A36").Select
ActiveSheet.Paste
ActiveSheet.PivotTables("PivotTable6").PivotFields("AircraftType"). _
ClearAllFilters
ActiveSheet.PivotTables("PivotTable6").PivotFields("AircraftType").CurrentPage _
= "ATR 42"
ActiveWindow.SmallScroll Down:=3
Range("A43").Select
ActiveSheet.Paste
ActiveSheet.PivotTables("PivotTable7").PivotFields("AircraftType"). _
ClearAllFilters
ActiveSheet.PivotTables("PivotTable7").PivotFields("AircraftType").CurrentPage _
= "ATR 72"
ActiveWindow.SmallScroll Down:=9
Range("A50").Select
ActiveSheet.Paste
ActiveSheet.PivotTables("PivotTable8").PivotFields("AircraftType"). _
ClearAllFilters
ActiveSheet.PivotTables("PivotTable8").PivotFields("AircraftType").CurrentPage _
= "CRJ100 Regional Jet"
ActiveWindow.SmallScroll Down:=3
Range("A57").Select
ActiveSheet.Paste
ActiveSheet.PivotTables("PivotTable9").PivotFields("AircraftType"). _
ClearAllFilters
ActiveSheet.PivotTables("PivotTable9").PivotFields("AircraftType").CurrentPage _
= "CRJ200 Regional Jet"
ActiveWindow.SmallScroll Down:=12
Range("A65").Select
ActiveSheet.Paste
ActiveSheet.PivotTables("PivotTable10").PivotFields("AircraftType"). _
ClearAllFilters
ActiveSheet.PivotTables("PivotTable10").PivotFields("AircraftType"). _
CurrentPage = "Q100"
Range("A72").Select
ActiveSheet.Paste
ActiveSheet.PivotTables("PivotTable11").PivotFields("AircraftType"). _
ClearAllFilters
ActiveSheet.PivotTables("PivotTable11").PivotFields("AircraftType"). _
CurrentPage = "Q200"
ActiveWindow.SmallScroll Down:=9
Range("A79").Select
ActiveSheet.Paste
ActiveSheet.PivotTables("PivotTable12").PivotFields("AircraftType"). _
ClearAllFilters
ActiveSheet.PivotTables("PivotTable12").PivotFields("AircraftType"). _
CurrentPage = "Q300"
ActiveWindow.SmallScroll Down:=9
Range("A86").Select
ActiveSheet.Paste
ActiveSheet.PivotTables("PivotTable13").PivotFields("AircraftType"). _
ClearAllFilters
ActiveSheet.PivotTables("PivotTable13").PivotFields("AircraftType"). _
CurrentPage = "Q400"
ActiveWindow.SmallScroll Down:=9
Range("A94").Select
ActiveSheet.Paste
ActiveSheet.PivotTables("PivotTable14").PivotFields("AircraftType"). _
ClearAllFilters
ActiveSheet.PivotTables("PivotTable14").PivotFields("AircraftType"). _
CurrentPage = "Q400 NextGen"
End Sub
I am a beginner so unable to understand how to apply for loop to automate this recorded code?
In the following macro, since your sample code didn't contain all 14 pages to be used for the pagefield, you'll need to complete the list being assigned to varPages before running the macro...
'Force the explicit declaration of variables
Option Explicit
Sub CreatePivotTables()
'Declare the variables
Dim varPages As Variant
Dim objPivotCache As PivotCache
Dim objPivotTable As PivotTable
Dim wksSource As Worksheet
Dim rngSource As Range
Dim CurrRow As Long
Dim i As Long
'Turn off screen updating to speed up macro
Application.ScreenUpdating = False
'Assign the source worksheet for the pivottables to wksSource
Set wksSource = Worksheets("Current Fleet Comparison")
'Assign the source range for the pivottables to rngSource
Set rngSource = wksSource.Range("A1").CurrentRegion
'Create the pivotcache for the pivottables
Set objPivotCache = ActiveWorkbook.PivotCaches.Create( _
SourceType:=xlDatabase, _
SourceData:=rngSource)
'Add new worksheet for the pivottables
Sheets.Add
'Assign the list of pages for the pagefield to varPages (add the remaining pages)
varPages = Array("A318", "A319", "A320", . . .)
CurrRow = 3
For i = 1 To 14
'Create the pivottable
Set objPivotTable = ActiveSheet.PivotTables.Add( _
PivotCache:=objPivotCache, _
TableDestination:=Cells(CurrRow, "A"), _
TableName:="PivotTable" & i)
'Add the fields for the pivottable
With objPivotTable
.AddDataField .PivotFields("AircraftType"), "Count of AircraftType", xlCount
.PivotFields("OperatorArea").Orientation = xlColumnField
With .PivotFields("AircraftType")
.Orientation = xlPageField
.CurrentPage = varPages(i - 1)
End With
With .TableRange2
CurrRow = .Offset(.Rows.Count + 4).Row
End With
End With
Next i
'Show the pivottable field list
ActiveWorkbook.ShowPivotTableFieldList = True
'Turn screen updating back on
Application.ScreenUpdating = True
End Sub
I have some code I run each morning that converts transactional data into a table then creates a Pivot Table based off of that data.
I have a button in a separate spreadsheet that I use to run these macros, but when I use the button the code formats the dates in US format not UK.
Sub TUFRFormat()
Application.DisplayAlerts = False
Columns("A:Y").Select
Selection.Columns.AutoFit 'Ensures data is displayed correctly
Columns("B:B").Select 'Rearanges columns to be presented correctly
Selection.Cut Destination:=Columns("Z:Z")
Columns("B:B").Select
Selection.Delete Shift:=xlToLeft
Range("F:F,G:G,H:H,I:I,J:J,U:U,V:V,W:W,X:X").Select
Selection.EntireColumn.Hidden = True 'Hides unrelevant columns
Range(Selection, Selection.End(xlToRight)).Select
Range(Selection, Selection.End(xlDown)).Select
ActiveSheet.ListObjects.Add(xlSrcRange, Range("$A$1:$Y$50000"), , xlYes).Name _
= "Table1"
Range("Table1[#All]").Select
ActiveSheet.ListObjects("Table1").TableStyle = "TableStyleLight9" 'Selects a table theme
Range("Table1[[#Headers],[Unit]]").Select
ChDir "P:\Desktop\Prior Day Journals\Tueday - Friday"
' Creates a pivot table based off of the sheet 'Data'
Sheets.Add After:=Sheets(Sheets.Count)
Sheets("Sheet1").Select
Sheets("Sheet1").Name = "Table" 'Adds new sheet and names it table
Sheets("Table").Select
Sheets("Table").Move Before:=Sheets(1) 'Moves to the first sheet in the document
ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
"Table1", Version:=xlPivotTableVersion14).CreatePivotTable TableDestination _
:="Table!R1C1", TableName:="PivotTable1", DefaultVersion:= _
xlPivotTableVersion14
Sheets("Table").Select
Cells(1, 1).Select
With ActiveSheet.PivotTables("PivotTable1").PivotFields("Posted")
.Orientation = xlPageField
.Position = 1
End With
With ActiveSheet.PivotTables("PivotTable1").PivotFields("Date")
.Orientation = xlPageField
.Position = 1
End With
With ActiveSheet.PivotTables("PivotTable1").PivotFields("Year")
.Orientation = xlColumnField
.Position = 1
End With
With ActiveSheet.PivotTables("PivotTable1").PivotFields("Period")
.Orientation = xlColumnField
.Position = 2
End With
With ActiveSheet.PivotTables("PivotTable1").PivotFields("Unit")
.Orientation = xlRowField
.Position = 1
End With
ActiveSheet.PivotTables("PivotTable1").AddDataField ActiveSheet.PivotTables( _
"PivotTable1").PivotFields("Sum Amount3"), "Count of Sum Amount3", xlCount
ActiveSheet.PivotTables("PivotTable1").RowAxisLayout xlOutlineRow
ActiveSheet.PivotTables("PivotTable1").PivotFields("Posted").CurrentPage = _
"(All)"
With ActiveSheet.PivotTables("PivotTable1").PivotFields("Posted")
.PivotItems("(blank)").Visible = False
End With
ActiveSheet.PivotTables("PivotTable1").PivotFields("Posted"). _
EnableMultiplePageItems = True
I have tried looking for an obvious answer, but when I run the code directly rather than through the button it formats the dates as the UK format.
Any help would be appreciated
I made a VBA macro that generates a MailMerge from an Excel spreadsheet creating the new document in Word.
I need to run a Find and Replace on a particular phrase ('ANTHXXXX') in the Word document with the user input variable InputtedModuleCode.
The macro runs without errors, but I can't get it to find and replace. I have included the entire macro script below. The relevant line of the script is underneath the comment:
' find and replace module code
...about 10 lines from the bottom of the script.
Sub AAMerge()
'
' AAMerge Macro
'
'
'Prompt user to input Module Code
Dim InputtedModuleCode As String
InputtedModuleCode = InputBox("Enter Module Code here, e.g. ANTH1001")
'Prompt user to input Module Code
Dim InputtedSubmissionDeadline As String
InputtedSubmissionDeadline = InputBox("Enter essay submission deadline. Must be format dd/mm/yyyy hh:mm:ss")
'Copy data into new spreadsheet
Cells.Select
Selection.Copy
Workbooks.Add
ActiveSheet.Paste
Application.CutCopyMode = False
With Selection.Font
.Name = "Arial"
.Size = 12
.StrikeThrough = False
.Superscript = False
.Subscript = False
.OutlineFont = False
.Shadow = False
.Underline = xlUnderlineStyleNone
End With
With Selection.Font
.Name = "Arial"
.Size = 10
.StrikeThrough = False
.Superscript = False
.Subscript = False
.OutlineFont = False
.Shadow = False
.Underline = xlUnderlineStyleNone
End With
' Move GradeMark Grade Column
Columns("H:H").Select
Selection.Copy
Columns("P:P").Select
ActiveSheet.Paste
' Delete Overlap/Internet Overlap/Publications Overlap/Student Papers Overlap columns
Columns("C:C").Select
Selection.Delete Shift:=xlToLeft
Selection.Delete Shift:=xlToLeft
Columns("F:J").Select
Selection.Delete Shift:=xlToLeft
' insert Portico SCN formula
Range("F2").Select
ActiveCell.FormulaR1C1 = "SCN (Portico)"
Range("F3").Select
ActiveCell.FormulaR1C1 = "=IFERROR(VLOOKUP((UPPER(CONCATENATE(RC[-5],""_"",(LEFT(RC[-4],1)),""_" & InputtedModuleCode & """))),'N:\EssaySubTrial\[Student List 201213.xls]Sheet1'!C1:C9,6,FALSE),"""")"
Range("F3").Select
Dim LR As Integer
LR = Range("A" & Rows.Count).End(xlUp).Row
Range("F3").AutoFill Destination:=Range("F3:F" & LR), Type:=xlFillDefault
' insert Portico student email
Range("G2").Select
ActiveCell.FormulaR1C1 = "Email (Portico)"
Range("G3").Select
ActiveCell.FormulaR1C1 = "=IFERROR(VLOOKUP((UPPER(CONCATENATE(RC[-6],""_"",(LEFT(RC[-5],1)),""_" & InputtedModuleCode & """))),'N:\EssaySubTrial\[Student List 201213.xls]Sheet1'!C1:C9,7,FALSE),"""")"
Range("G3").Select
LR = Range("A" & Rows.Count).End(xlUp).Row
Range("G3").AutoFill Destination:=Range("G3:G" & LR), Type:=xlFillDefault
' insert Portico student department name
Range("H2").Select
ActiveCell.FormulaR1C1 = "Dept (Portico)"
Range("H3").Select
ActiveCell.FormulaR1C1 = "=IFERROR(VLOOKUP((UPPER(CONCATENATE(RC[-7],""_"",(LEFT(RC[-6],1)),""_" & InputtedModuleCode & """))),'N:\EssaySubTrial\[Student List 201213.xls]Sheet1'!C1:C9,9,FALSE),"""")"
Range("H3").Select
LR = Range("A" & Rows.Count).End(xlUp).Row
Range("H3").AutoFill Destination:=Range("H3:H" & LR), Type:=xlFillDefault
' Format column headers and widths
Rows("2:2").Select
Selection.Font.Bold = True
Columns("G:G").EntireColumn.AutoFit
Columns("H:H").EntireColumn.AutoFit
'Sort alphabetically by surname/firstname
Range("A3").Select
ActiveWorkbook.Worksheets("Sheet1").Sort.SortFields.Clear
ActiveWorkbook.Worksheets("Sheet1").Sort.SortFields.Add Key:=Range("A3:A" & LR) _
, SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
ActiveWorkbook.Worksheets("Sheet1").Sort.SortFields.Add Key:=Range("B3:B" & LR) _
, SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
With ActiveWorkbook.Worksheets("Sheet1").Sort
.SetRange Range("A2:H" & LR)
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
' Move SCN column from Column G to Column C
Columns("C:C").Select
Selection.Insert Shift:=xlToRight
Columns("G:G").Select
Selection.Cut Destination:=Columns("C:C")
Columns("C:C").Select
' Remove ' at ' from Date Uploaded column
Columns("F").Replace What:=" at ", Replacement:=" ", LookAt:=xlPart
' Format date and add extra date columns
Columns("F:F").Select
Selection.NumberFormat = "dd/mm/yyyy hh:mm:ss"
Selection.Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
Selection.Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
Range("G2").Select
ActiveCell.FormulaR1C1 = "Extension Date"
Range("F2").Select
ActiveCell.FormulaR1C1 = "Essay Deadline"
Columns("F:G").Select
Selection.NumberFormat = "dd/mm/yyyy hh:mm:ss"
' Add user inputted submission date
Range("F3").Select
ActiveCell.FormulaR1C1 = CDate(InputtedSubmissionDeadline)
Range("F3").Select
LR = Range("A" & Rows.Count).End(xlUp).Row
Range("F3").AutoFill Destination:=Range("F3:F" & LR), Type:=xlFillCopy
' Cleanup column width and add extra column
Columns("F:F").EntireColumn.AutoFit
Range("I2").Select
ActiveCell.FormulaR1C1 = "Days late"
Columns("J:J").Select
Selection.Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
Range("J2").Select
ActiveCell.FormulaR1C1 = "Penalty (%pts)"
' Number of days late column
Range("I3").Select
ActiveCell.FormulaR1C1 = _
"=IF((RC[-1]-(IF(RC[-2]=0,RC[-3],RC[-2]))<=0), 0, (ROUNDUP(RC[-1]-(IF(RC[-2]=0,RC[-3],RC[-2])),0)))"
Range("I3").Select
LR = Range("A" & Rows.Count).End(xlUp).Row
Range("I3").AutoFill Destination:=Range("I3:I" & LR), Type:=xlFillDefault
' Penalty %pts column
Range("J3").Select
ActiveCell.FormulaR1C1 = _
"=(IF(RC[-1]>7,100,(IF(RC[-1]>1,10,IF(RC[-1]>0,5,0)))))"
Range("J3").Select
LR = Range("A" & Rows.Count).End(xlUp).Row
Range("J3").AutoFill Destination:=Range("J3:J" & LR), Type:=xlFillDefault
' Add marks columns
Range("M2").Select
ActiveCell.FormulaR1C1 = "1stM Grade"
Range("N2").Select
ActiveCell.FormulaR1C1 = "2ndM Grade"
Range("O2").Select
ActiveCell.FormulaR1C1 = "Final Grade"
Range("O2").Select
ActiveCell.FormulaR1C1 = "Agreed Grade"
' Add final grade colum
Range("P2").Select
ActiveCell.FormulaR1C1 = "Final Grade (after penalty)"
Range("P3").Select
ActiveCell.FormulaR1C1 = "=MAX(0,(RC[-1]-RC[-6]))"
Range("P3").Select
LR = Range("A" & Rows.Count).End(xlUp).Row
Range("P3").AutoFill Destination:=Range("P3:P" & LR), Type:=xlFillDefault
' Add column with formatted submission deadline date that can be read by MailMerge in word
Range("Q2").Select
ActiveCell.FormulaR1C1 = "Submission Deadline (formatted)"
Range("Q3").Select
ActiveCell.FormulaR1C1 = "=TEXT(RC[-11],""dd-mmm-YYYY HH:mm:ss"")"
Range("Q3").Select
LR = Range("A" & Rows.Count).End(xlUp).Row
Range("Q3").AutoFill Destination:=Range("Q3:Q" & LR), Type:=xlFillDefault
' Add column with formatted submission deadline date that can be read by MailMerge in word
Range("R2").Select
ActiveCell.FormulaR1C1 = "Date Uploaded (formatted)"
Range("R3").Select
ActiveCell.FormulaR1C1 = "=TEXT(RC[-10], ""dd-mmm-YYYY HH:mm:ss"")"
Range("R3").Select
LR = Range("A" & Rows.Count).End(xlUp).Row
Range("R3").AutoFill Destination:=Range("R3:R" & LR), Type:=xlFillDefault
'Save file
ActiveWorkbook.SaveAs Filename:="N:\EssaySubTrial\" & InputtedModuleCode & " Datasheet " & _
Format(Now(), "yyyy-mm-dd HHmmss") & ".xlsx", FileFormat:=xlOpenXMLWorkbook, Password:="", _
WriteResPassword:="", ReadOnlyRecommended:=False, CreateBackup:=False
Sheets("Sheet3").Select
ActiveWindow.SelectedSheets.Delete
Sheets("Sheet2").Select
ActiveWindow.SelectedSheets.Delete
' do Mailmerge
Dim wdOutputName, wdInputName As String
wdOutputName = ThisWorkbook.Path & "\Coversheet " & Format(Date, "d mmm yyyy")
wdInputName = ThisWorkbook.Path & "\coursework-coversheet-template-merged-updated.docx"
' open the mail merge layout file
Dim wdDoc As Object
Set wdDoc = GetObject(wdInputName, "Word.document")
wdDoc.Application.Visible = True
With wdDoc.MailMerge
.MainDocumentType = wdFormLetters
.Destination = wdSendToNewDocument
.SuppressBlankLines = True
.Execute Pause:=False
End With
' find and replace module code
wdDoc.Application.ActiveDocument.Content.Find.Execute "ANTHXXXX", ReplaceWith:=InputtedModuleCode, Replace:=wdReplaceAll
' show and save output file
wdDoc.Application.Visible = True
wdDoc.Application.ActiveDocument.SaveAs wdOutputName
' cleanup
wdDoc.Close SaveChanges:=False
Set wdDoc = Nothing
End Sub
I haven't check the remainder of the code but if your problem is merely the Find and replace at the bottom of the code then the following should do the job (setting the replacement from a string shouldn't matter):
'I'd recommend leaving all these options in
With wdDoc.Application.Selection.Find
.ClearFormatting
.Text = "ANTHXXXX"
.Replacement.Text = InputtedModuleCode
.Forward = True
.Wrap = wdFindContinue
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchKashida = False
.MatchDiacritics = False
.MatchAlefHamza = False
.MatchControl = False
.MatchByte = False
.MatchAllWordForms = False
.MatchSoundsLike = False
.MatchFuzzy = False
.MatchWildcards = True
.Execute Replace:=wdReplaceAll
End With
One other thing if you're interested, the code wdDoc.Application.ActiveDocument.SaveAs does exactly the same thing as wdDoc.SaveAs.
I have an existing .xlsm file that runs perfectly with all of the macros. The problem is that when I attempt to record another macro, I add a column, press enter, and get the message "Microsoft Excel has stopped responding". I then have to end the process. I am assuming that this has something to do with the existing macro which was imported from Excel 2003 and modified to work for 2010.
Are there any incompatabilities within this macro that could cause this issue?
Sub Auto_Open()
Wbname = ActiveWorkbook.Name ' this needs to be first so the move works properly
fileToOpen = Application.GetOpenFilename("CSV files (*.csv), *.csv", 1, "Select file to open")
If fileToOpen <> False Then
Workbooks.Open (fileToOpen)
End If
sheetname = ActiveSheet.Name
Sheets(sheetname).Select
Sheets(sheetname).Move Before:=Workbooks(Wbname).Sheets(1)
Call Weekly_RTP
End Sub
Sub Weekly_RTP()
'
' Macro recorded 01/12/12 by Robert Gagliardi
'
' This next section (up to call sort_data) is needed until we get the formatting correct.
' Clearing the last rows and adding misc headers will solve the short term problem
' Need this once pivot table is created. Can't have heading row without names in it
Range("L1").Select
ActiveCell.FormulaR1C1 = "Misc"
Range("M1").Select
ActiveCell.FormulaR1C1 = "Misc1"
Columns("N:Z").Select
Selection.ClearContents
Call Sort_data
' concat mui & object to make it easy to find dups use countifs once at excel 2007 or greater
Range("N1").Select
ActiveCell.FormulaR1C1 = "Junk"
Range("N2").Select
ActiveCell.FormulaR1C1 = "=RC[-7]&RC[-5]"
Range("N2").Select
Selection.Copy
' need to find last row using column K2
lastrow = ActiveSheet.Range("K2").End(xlDown).Select
' Selection.Offset(0, 3).Select Moves over 3 cells
Range("N2", Selection.Offset(0, 3)).Select
ActiveSheet.Paste
Application.CutCopyMode = False
Columns("C:C").Select
Selection.Insert Shift:=xlToRight
Range("C1").Select
ActiveCell.FormulaR1C1 = "Alerts"
Range("C2").Select
ActiveCell.FormulaR1C1 = "=IF(COUNTIF(R2C[12]:RC15,RC[12])=1,COUNTIF(C[12],RC[12]),"" "")"
Range("C2").Select
Selection.Copy
' need to find last row using column B2 since column C was just added
lastrow = ActiveSheet.Range("B2").End(xlDown).Select
' Selection.Offset(0, 1).Select Moves over 1 cell from last cell in column B
Range("C2", Selection.Offset(0, 1)).Select
ActiveSheet.Paste
Application.CutCopyMode = False
Call Create_pivot
Call Save_data
' how to select a range of cells with data in them
' Worksheets(ActiveSheet.Name).Activate
' ActiveCell.CurrentRegion.Select
End Sub
Sub Create_pivot()
Wbname = ActiveWorkbook.Name
' Insert columns to make room for pivot table
Columns("A:I").Select
Selection.Insert Shift:=xlToRight
myData = Sheets(ActiveSheet.Name).[J1].CurrentRegion.Address
mySheet = ActiveSheet.Name & "!"
tableDest = "[" & Wbname & "]" & mySheet & "R1C1"
ActiveWorkbook.PivotCaches.Add(SourceType:=xlDatabase, SourceData:= _
mySheet & myData).CreatePivotTable TableDestination:=tableDest, TableName _
:="RTP_alerts", DefaultVersion:=xlPivotTableVersionCurrent
With ActiveSheet.PivotTables("RTP_alerts").PivotFields("Application")
.Orientation = xlRowField
.Position = 1
End With
With ActiveSheet.PivotTables("RTP_alerts").PivotFields("Object")
.Orientation = xlRowField
.Position = 2
End With
ActiveSheet.PivotTables("RTP_alerts").AddDataField ActiveSheet.PivotTables( _
"RTP_alerts").PivotFields("Alerts"), "Count of Alerts", xlCount
ActiveWorkbook.ShowPivotTableFieldList = False
Application.CommandBars("PivotTable").Visible = False
Columns("G:I").Select
Selection.Delete Shift:=xlToLeft
Range("D2").Select
ActiveCell.FormulaR1C1 = "Owner"
Range("E2").Select
ActiveCell.FormulaR1C1 = "Problem Ticket"
Columns("E:E").ColumnWidth = 13
Range("F2").Select
ActiveCell.FormulaR1C1 = "Comments"
Columns("F:F").ColumnWidth = 48
End Sub
Sub Save_data()
Filename = ActiveWorkbook.Name
Do
Fname = Application.GetSaveAsFilename(Filename, fileFilter:="Excel Files (*.xlsm), *.xlsm")
Loop Until Fname <> False
ActiveWorkbook.SaveAs Filename:=Fname, FileFormat:=52
End Sub
Sub Sort_data()
Columns("A:M").Select
Selection.Sort Key1:=Range("G2"), Order1:=xlAscending, Key2:=Range("I2") _
, Order2:=xlAscending, Header:=xlGuess, OrderCustom:=1, MatchCase:= _
False, Orientation:=xlTopToBottom, DataOption1:=xlSortNormal, DataOption2 _
:=xlSortNormal
Range("A1").Select
End Sub
I experienced the same problem, here's something you can try. Go to start-->run, and type %temp% in the box. This will bring up your temporary files.
Delete all or some of them, restart your computer and try again.