Search code examples
vbapowerpoint

Slide count variable in VBA - Powerpoint


@james wrote a while back in response to a similar question that the proper way to fo this is:

Sub CreatePres()
    Dim ppApp As PowerPoint.Application
    Dim ppPres As PowerPoint.Presentation
    Dim ppSlide As PowerPoint.Slide
    Dim ppTextbox As PowerPoint.Shape

    Set ppApp = New PowerPoint.Application
    ppApp.Visible = True
    ppApp.Activate

    Set ppPres = ppApp.Presentations.Add
    slidesCount = ppPres.Slides.Count
    Set ppSlide = ppPres.Slides.Add(slidesCount + 1, ppLayoutTitle)
    ppSlide.Shapes(1).TextFrame.TextRange.Text = "Hello world"
    ppSlide.Shapes(2).TextFrame.TextRange.Text = Date
    slidesCount = ActiveWindow.Selection.SlideRange.SlideIndex
    Call slide2(slidesCount)
End Sub

Sub slide2(i As Integer)
    Set ppSlide = ppPres.Slides.Add(i + 1, ppLayoutTitle)
    ppSlide.Select
    ppSlide.Shapes(1).TextFrame.TextRange.Text = "Hello world"
    ppSlide.Shapes(2).TextFrame.TextRange.Text = Date
End Sub

I am however getting a "By ref mismatch Argumnenr error on the 'Call Slide2(slidecount)'-- it's the las line of the first sub.

I'm using Office 365 on Windows 10 Pro.

Thanks in advance


Solution

  • You didn't DIM your slidesCount variable, so VBA creates a variant when you assign a value to it. Your Sub slide2 expects an integer, so it throws an error.

    To save further trouble like this, ALWAYS put Option Explicit at the top of every module. That'll prevent undeclared variables from causing problems like this.

    Go to Tools | Options and put a check next to Require Variable Declaration to have VBA automatically insert Option Explicit for you.

    It's also a good idea to use the correct variable type. Any .Count value in the PPT object model will be a Long, not an integer. VBA will generally convert between the two when it figures it needs to. Usually it's right. Sometimes it's not. Then it all hits the fan.