Search code examples
vbapowerpoint

Changing the Fill Color


I am pretty new to VBA and want to make a macro that inserts a shape in the top right corner that says TBU when i run it. I am trying to have the fill color be bright yellow (255,255,0), and can get the code to work with everything except fill color.

I think I am having some trouble understanding the With function - so it would be great if you could also breifly explain what i was doing wrong!

Thanks so much!!

Sub TBU()

Dim oSh As Shape
Dim myDocument As Presentation
Dim oSl As Slide
Dim sTitle As String

sTitle = "TBU"

Set myDocument = ActivePresentation

Set oSl = myDocument.Slides(Application.ActiveWindow.View.Slide.SlideIndex)

Set oSh = oSl.Shapes.AddTextbox(msoTextOrientationHorizontal, _
    Left:=600, Top:=10, Width:=155, Height:=50)
    
With Shape
    .Fill.ForeColor.RGB = RGB(255, 255, 0)
End With
    
With oSh.TextFrame.TextRange
    .Text = sTitle
    With .Font
        .Size = 24
        .Name = "Arial"
    End With
End With

End Sub

Solution

  • You asked about using With. It saves typing and at least in theory, makes things run a bit faster.

    Instead of your code, you could use:

    With oSh
        .Fill.ForeColor.RGB = RGB(255, 255, 0)
        
        With .TextFrame.TextRange
           .Text = sTitle
          With .Font
            .Size = 24
            .Name = "Arial"
          End With  ' Font
       End With  ' TextRange
    End With  'oSh
    

    The 'comments after each End With statement are optional, but it helps keep track of things with nested With statements.

    And to expand on FunThomas' suggestion, it's a very good idea to put Option Explicit at the top of every module. That'll force you to declare all variables and will point out problems with mistyped variable names.

    Better yet, in the VBA editor, choose Tools | Options and on the Editor tab, put a check next to Require Variable Declaration. That'll put Option Explicit at the top of each new module, automatically.