Search code examples
vbaif-statementpowerpoint

Apply If Then statement with Or operator to determine am/pm


I have a presentation with a picture on each slide. The name of the picture contains the date and time the picture was taken. There is a textbox on every slide.

My goal is to populate the textbox with the name, date and time of the picture.

I have a way to input the name and date of the picture.

I am having trouble classifying the time of the picture as pm or am. I am attempting to use an If Then Else statement. All times say pm.

The If Then statement is on line 29.

Sub PlaceNameofPictureInEverySlideEdit()

    Dim sld As Slide
    Dim shp As Shape
    Dim PicName As String
    Dim PicDate As String
    Dim PicDateDate As Date
    Dim PicDate1 As String
    Dim PicDate2 As String
    Dim PicDate3 As String
    Dim PicDate4 As String
    Dim PicDate5 As String
    Dim PicDate6 As String
    Dim DayNight As String

    For Each sld In Application.ActivePresentation.Slides
        For Each shp In sld.Shapes
            If shp.Type = msoPicture Then
                PicName = shp.Name
            End If
        Next
        
        For Each shp In sld.Shapes
            If shp.HasTextFrame Then
                PicDate = shp.TextFrame.TextRange.Characters(1, 10)
                PicDate1 = shp.TextFrame.TextRange.Characters(6, 2)
                PicDate2 = shp.TextFrame.TextRange.Characters(9, 2)
                PicDate3 = shp.TextFrame.TextRange.Characters(1, 4)
                PicDate4 = shp.TextFrame.TextRange.Characters(12, 2)
                PicDate5 = shp.TextFrame.TextRange.Characters(15, 2)
                PicDateDate = CDate(PicDate)

                If PicDate4 = "12" Or "13" Or "14" Or "15" Or "16" Or "17" Or "18" Or "19" Or "20" Or "21" Or "22" Or "23" Then
                    DayNight = " pm"
                Else: DayNight = " am"
                End If
       
                shp.TextFrame.TextRange.Text = PicName & vbNewLine & PicDateDate _
                  & vbNewLine & PicDate4 & ":" & PicDate5 & DayNight
                
                With shp
                    .TextFrame.TextRange.Replace(FindWhat:=".jpg", ReplaceWhat:="") = ""
                    shp.Top = 473.5449
                    shp.Left = 536.4305
                End With
            End If
        Next
    Next

End Sub

Solution

  • In VBA, you have to repeat the left side of the condition when using And/Or:

    If PicDate4 = "12" Or "13" Or "14" Or "15" Or "16" Or "17" Or "18" Or "19" Or "20" Or "21" Or "22" Or "23" Then
    

    should be

    If PicDate4 = "12" Or PicDate4 = "13" Or PicDate4 = "14"...
    

    There are several ways to simplify this; one is Select Case:

    If IsNumeric(PicDate4) Then
        Select Case CLng(PicDate4)
            Case 12 To 23
                DayNight = " pm"
            Case Else
                DayNight = " am"
        End Select
    End If