PDA

View Full Version : [SOLVED:] vba to set slide background with vertical gradients



NickyC
07-27-2015, 11:06 PM
Hi

I am trying to use VBA to set a slide's background to vertical gradients of different colours. I can create a shape with gradients, but when I try to apply the code to the slide background I get a message saying gradients stops can only be accessed on shapes with gradient fill.

This is what I have tried. I am probably just missing one line of code, but can't work out what it is.



[Sub BackGradients()
Dim MyDoc As Slide, Col1, Col2, Col3, Col4
Set MyDoc = ActivePresentation.Slides(1)
Col1 = RGB(255, 0, 0) 'red
Col1 = RGB(0, 255, 0) 'green
Col1 = RGB(0, 0, 255) 'blue
Col1 = RGB(0, 255, 255) 'yellow
With MyDoc.Background.Fill
.GradientStops.Insert Col1, 0.25
.GradientStops.Insert Col2, 0.5
.GradientStops.Insert Col3, 0.75
End With
End Sub

John Wilson
07-28-2015, 05:11 AM
I haven't worked much with the new gradients but it looks like you need to start with a preset


Sub BackGradients()
Dim MyDoc As Slide, Col1 As Long, Col2 As Long, Col3 As Long, Col4 As Long, col5 As Long
Dim i As Integer
Set MyDoc = ActivePresentation.Slides(1)
'temporary gradient
MyDoc.Background.Fill.TwoColorGradient msoGradientVertical, 1
Col1 = RGB(255, 0, 0) 'red
Col2 = RGB(0, 255, 0) 'green
Col3 = RGB(0, 0, 255) 'blue
Col4 = RGB(255, 255, 0) 'yellow
col5 = RGB(0, 255, 255) 'cyan
With MyDoc.Background.Fill
' change 1,2 add rest
.GradientStops(1).Color = Col1
.GradientStops(1).Position = 0#
.GradientStops(2).Color = Col2
.GradientStops(2).Position = 0.25
.GradientStops.Insert Col3, 0.5
.GradientStops.Insert Col4, 0.75
.GradientStops.Insert col5, 1#
End With
End Sub

NickyC
07-28-2015, 06:08 PM
Thanks for that, John
When I try it on a slide with no background, I still get the error message "gradient stops can only be accessed on shapes with gradient fill".
However, when I apply a standard gradient first to the slide and then run the macro, it works. So I got there in the end.

John Wilson
07-29-2015, 03:38 AM
This might work better


Sub BackGradients()
Dim MyDoc As Slide, Col1 As Long, Col2 As Long, Col3 As Long, Col4 As Long, col5 As Long
Dim i As Integer
Set MyDoc = ActivePresentation.Slides(1)
'temporary gradient
MyDoc.FollowMasterBackground = False
MyDoc.Background.Fill.TwoColorGradient msoGradientVertical, 2
Col1 = RGB(255, 0, 0) 'red
Col2 = RGB(0, 255, 0) 'green
Col3 = RGB(0, 0, 255) 'blue
Col4 = RGB(255, 255, 0) 'yellow
col5 = RGB(0, 255, 255) 'cyan
With MyDoc.Background.Fill
' change 1,2 add rest
.GradientStops(1).Color = Col1
.GradientStops(1).Position = 0#
.GradientStops(2).Color = Col2
.GradientStops(2).Position = 0.25
.GradientStops.Insert Col3, 0.5
.GradientStops.Insert Col4, 0.75
.GradientStops.Insert col5, 1#
End With
End Sub

NickyC
07-29-2015, 06:04 PM
Yes thanks John, works perfectly!