Excel VBA to Create Header ERROR - vba

I am currently using the below macro to customize the header based off the contents of cell B3 within spreadsheet "Reference", and have been using it sometime now.
I'm currently running into an issue where the header font is becoming very large. The header becomes so large, that if I print the spreadsheet (which I do often with this file) it monopolizes the entire page - in other words - the header overtakes the entire print area because it's so large.
Is anyone able to see where I'm going wrong with the macro or have an idea as to why this is occurring and how to resolve this issue?
----
'=========================================================================
' Custom Header based on value of specified cell
'=========================================================================
Sub HeaderFont()
ActiveSheet.PageSetup.RightHeader = "&""Calibri,bold""&11" & Sheets("Reference").Range("B3")
End Sub

Maybe you would be interested by something like the code below.
It checks the length of the string in cell "B3" and according to the length (using Select Case) it sets the Header font size. You will need to adjust the values inside the Cases to fit your needs.
Option Explicit
'=========================================================================
' Custom Header based on value of specified cell
'=========================================================================
Sub HeaderFont()
Dim FntSize As Integer
Select Case Len(Sheets("Reference").Range("B3"))
Case Is > 300 ' <-- length of string is more than 300 characters
FntSize = 11
Case Is > 200 ' <-- length of string is more than 200 characters
FntSize = 12
Case Else
FntSize = 13
' you can add more Cases to have more scenarios
End Select
ActiveSheet.PageSetup.RightHeader = "&""Calibri,Bold""&" & FntSize & "" & Sheets("Reference").Range("B3")
End Sub

Related

Superscript Formatting Erased when Text is stored in String

Dim ST As String
ST = ActiveDocument.Paragraphs(1).Range.Text
In my document, Paragraphs(1) is actually 2 + 32. However, with Debug.Print ST, the output is 2 + 32. Is there any way to store the data without compromising the superscript and subscript formatting?
The objective behind this is to store 5 lines in ST(1 to 5) and then shuffle the order of the 5 lines.
1 - It is not clear how do you want to capture the paragraphs so I'm assuming that you will have those paragraphs selected, modify it based on your requirement
2 - It is also not clear on what shuffle means so I will assume that you want it to be reversed, you will need to come out with your own logic on how to shuffle the paragraphs:
FormattedText property can be used to replace a range with formatted text so this should work for you:
Private Sub ShuffleSelectedParagraphs()
ActiveDocument.Content.InsertParagraphAfter
Dim i As Long
For i = Selection.Paragraphs.Count To 1 Step -1
ActiveDocument.Content.Paragraphs.Last.Range.FormattedText = Selection.Paragraphs(i).Range.FormattedText
Next
End Sub
You will need to select the paragraphs first then run the Sub, it will duplicate the selected paragraphs at the end of the document but in the reverse order.

Dynamic Named Range with Moving Data Below

I am trying to create a dynamic named range that I can use for a data validation list. I use these all time but in this case I have information that is housed below the range that cannot be counted in the range. Also, I have a macro that insert rows within this range that do need to be counted.
I normally would use something like this if nothing else was in the column: =OFFSET($A$1,0,0,COUNTA($A:$A),1)
I need to start this one down the page a little ways so I used:
=OFFSET($A$24,0,0,COUNTA($A$24:$A24),1)
Notice I have removed the "$" before the last "24" in the formula hoping it would expand accordingly, but that does not seem to be consistent.
Basically, I need the COUNTA range to only include a range of cells that will always be growing and shrinking.
I'm not bad in VBA and am open to a solution that might include looping through a range of cells and stopping once it reaches a cell that's value equals a certain text string (in the case in would be .Value = "Request 1"). But I am a little apprehensive about feeding a form or ActiveX Control, as this has caused me issues in the past with viewing and printing functionality.
I used a the following code to create a range elsewhere in the workbook that I could then easily use to create a dynamic named range:
Sub UpdateEntities()
Dim i As Long, x As Long
i = 24
x = 1
Sheets("Values").Range("AH:AH").ClearContents
Do While Cells(i, 1).Value <> "REQUEST 1"
Cells(i, 1).Select
If ActiveCell.Value <> "" Then
Sheets("Values").Cells(x, 34).Value = ActiveCell.Value
i = i + 1
x = x + 1
Else
i = i + 1
End If
Loop
End Sub

Excel VBA Pivot Table Fill Header

In excel vba I am creating a pivot table and want to fill the header (first two rows) and bottom line (1 row) blue with white font.
The below code fills in the interior of the first data set row rather than the header.
With ActiveSheet.PivotTables(1).TableRange1
.Cells.Borders.LineStyle = xlContinuous
.Range("A3:I4").Interior.ColorIndex = 49
.Range("A13:I13").Interior.ColorIndex = 49
End With
Is there a way to dynamically reference the header and the last line of the pivot table? It would be better to reference "pivot table header" than specific ranges incase values of the report change.
you can simply use this:
With ActiveSheet.PivotTables("PivotTable1")
Debug.Print "full headers at: " & Intersect(.Parent.Range(.TableRange1.Row & ":" & .DataBodyRange.Row - 1), .TableRange1).Address
Debug.Print "last row-range at: " & .TableRange1.Rows(1).Offset(.TableRange1.Rows.Count - 1).Address
End With
but looking at your sub, the easiest way would be to change:
.Range("A3:I4").Interior.ColorIndex = 49
.Range("A13:I13").Interior.ColorIndex = 49
to:
Union(.Rows("1:2"), .Rows(.Rows.Count)).Interior.ColorIndex = 49
There is a dynamic way to address the header rows and the last row:
Dim pvtFirstRow, pvtLastRow As Integer
pvtFirstRow = ActiveSheet.PivotTables(1).TableRange1.row + x ' modify x to the first row where your Pivot data starts
pvtLastRow = ActiveSheet.PivotTables(1).TableRange1.Cells(ActiveSheet.PivotTables(1).TableRange1.Cells.count).row
The code presented in the thread so far does work, but will have to be rerun in future: Any time the number of rows or columns in the pivot changes, you may sit with coloured rows or columns where there is no pivot, or coloured cells in the wrong part of the pivot.
I suggest you look at the built in pivot styles of Excel, pick the one closest to what you need, and use code like this to modify the header row(s) and the grand total row. There is no need to manipulate ranges of cells, because next time you might want to turn off the total row (for argument's sake) but the range will still be coloured.
I recorded a macro and removed all redundant lines of code to help you see what changes. I also remove one useful row (.TintAndShade = ) and replaced it with a "ColorIndex = " statement in order to force the shade of blue you seem to prefer.
After running this, you should have the same style available to all other (existing and new) pivots in the same workbook. You could even make it default. No need to run code again to format when your pivot [refreshed] covers a different range of cells.
You can pick another style one from your own palette and use your own custom name for the copy, as long as you find and replace all relevant strings in the sample code below or record your own actions:
Sub ColourPivotStyleForThisBook()
'duplicate blue/medium pivot style from template
ActiveWorkbook.TableStyles("PivotStyleMedium2").Duplicate ("PivotStyleMedium2v2" _
)
With ActiveWorkbook.TableStyles("PivotStyleMedium2v2")
.ShowAsAvailablePivotTableStyle = True
.ShowAsAvailableTableStyle = False
.ShowAsAvailableSlicerStyle = False
.ShowAsAvailableTimelineStyle = False
End With
'now modify header's style (fill) (font colour is white/automatic already)
With ActiveWorkbook.TableStyles("PivotStyleMedium2v2").TableStyleElements( _
xlHeaderRow).Interior
'only one/two lines are changing the colours
' .TintAndShade = -0.249977111117893
.ColorIndex = 49
End With
'now modify grand total row's style (fill) (font colour is white/automatic already)
With ActiveWorkbook.TableStyles("PivotStyleMedium2v2").TableStyleElements( _
xlTotalRow).Interior
'only one/two lines are changing the colours
' .TintAndShade = -0.249946592608417
.ColorIndex = 49
End With
End Sub
If the result you get is not what you're after, simply select part of a pivot in the workbook, tap the Design tab of the PivotTable Tools ribbon, right-click on the one your code has created (it should be in the Custom section at the top), and click Delete. Hope this helps.
(You can even use code like the above to customise PivotTable styles in other workbooks that don't have PivotTables yet.)

Macro query spread over multiple-sheets

Wording my question is slightly tricky so I've included screen-shots to make this easier. I have 2 separate spreadsheets which are currently not linked together in anyway. What I've been asked to do is:
For the drop-downs which have a * next to them, have this * drop-down get converted into a acronym (I.e. If it's Home Visit *, then this will be converted to HV), and have it automatically entered into Cell Position X. Please refer to Image 1 then Image 2)
So the user would click on Sheet one, select the relevant drop-down field and then assign how much time that task took. The second sheet would then update itself with this information - it would insert the users name, program and activities. This is where it gets very tricky. Based off the drop-down selection, if it is asterisked (*), then based off the field-type it will convert it into a set acronym which would then be placed in one of the data fields based off the entry date that has been provided.
I designed both spread-sheets and they have macros in the background, but I can't seem to work out how to best perform this. Would you suggest a transpose function which checks firstly the date criteria and then an INDEX(MATCH) function to match the criteria against a pre-defined name-range which converts Home Visit etc. to HV automatically? I'm also unsure of how to insert delimiters for each new entry that is read. If anyone can provide help I would be very grateful.
I'm not 100% sure I understand your question, but here goes:
What about adding a Worksheet_Change event to look for changes in the drop-down's cell, and then converting it to an acronym?
Place the following code inside the sheet of interest:
Private Sub Worksheet_Change(ByVal Target As Range)
'If Cell A1 is changed, put the acronym into A2
If Target.Row = 1 And Target.Column = 1 Then
Cells(2, 1) = GetAcronym(Target.Value)
End If
End Sub
Function GetAcronym(TheText As String) As String
Dim result As String
Dim x As Long
'Always grab the first letter
result = Mid(TheText, 1, 1)
'Get the other letters
For x = 2 To Len(TheText) - 1
If Mid(TheText, x, 1) = " " Then result = result & Mid(TheText, x + 1, 1)
Next x
GetAcronym = UCase(result)
End Function

How to insert column in powerpoint using VBA

The questions is bit tricky one, I have googled and got a link http://joelblogs.co.uk/2010/08/13/automatically-create-summary-slides-in-powerpoint-2010/ with VBA code which helps me to insert summary of the titles of all the other slides of one presentation in single parent slide.
The code is working fine, however when the number of slides with titles is more than 30 or 50 then the Table of content parent slide cannot hold the entire title names as the names will be hidden and go beyond the slide presentation.
Hence, I like to confirm are there any VBA code to distribute the contents of the summary names in to three columns through VBA in the table of contents slide ?
Based on the link where you have an example you need to add that code at the and of your macro:
With summary.Shapes(2).TextFrame2
.Column.Number = 3
End With
which set 3 columns in your summary text frame.
Remember, that you could need to set font size, too, to keep your text within text box.
Additional information: What I see is that font size changes (decrease) as long as you put more text into summary Shape (Shapes(2) in my example). You could then trace the font size to check if you should increase number of columns. Here is an example:
With summary.Shapes(2).TextFrame2
If .TextRange.Font.Size < 20 Then
'additionally check here if max approved column numbers is not exceeded.
.Column.Number = .Column.Number + 1
End If
End With
And here is my full basic test code (which could be run for any new empty presentation):
Sub test_loop()
Dim summary As Slide
Set summary = ActivePresentation.Slides.Add(1, ppLayoutText)
Dim enterText as string
Do
enterText = InputBox("Additional text to insert into Shape:")
With summary.Shapes(2).TextFrame2
.TextRange.Text = .TextRange.Text & Chr(10) & enterText
If .TextRange.Font.Size < 20 Then
.Column.Number = .Column.Number + 1
End If
End With
Loop While enterText <> ""
End Sub