Отличия Ma c против Windows со строками / абзацами при манипулировании TextRange - PullRequest
0 голосов
/ 04 мая 2020

ОБНОВЛЕНИЕ

Я обнаружил, что vbCrLf является vbLf на ma c - и { ссылка } пришли к тому же выводу параллельно. Теперь я также узнал, что в Ma c TextRange интерпретируется как ЛИНИИ вместо ПАРАГРАФОВ.

Чтобы создать повестку дня и затем удалить первые два абзаца, мне понадобился этот код:

                    With ActivePresentation.SectionProperties
                    MsgBox "We gather now the Section headers"
                        For iSectIndex = 1 To .Count
                        If ActivePresentation.SectionProperties.Name(iSectIndex) <> "" Then
                            #If Mac Then

                            sSectionCollector = sSectionCollector & vbLf & ActivePresentation.SectionProperties.Name(iSectIndex)
                            #Else
                            sSectionCollector = sSectionCollector & vbCrLf & ActivePresentation.SectionProperties.Name(iSectIndex)
                            #End If
                        End If
                        Next iSectIndex
                    End With

                    sAgendaTextblock.TextFrame2.TextRange.Text = sSectionCollector

                    #If Mac Then
                    MsgBox "starting to delete"
                    MsgBox "line 1: " & sAgendaTextblock.TextFrame2.TextRange.Paragraphs(1).Lines(1).Text
                    sAgendaTextblock.TextFrame2.TextRange.Paragraphs(1).Lines(1, 2).Delete

                    #Else
                    MsgBox "starting to delete"
                    MsgBox "paragraph 1: " & sAgendaTextblock.TextFrame2.TextRange.Paragraphs(1).Text
                    sAgendaTextblock.TextFrame2.TextRange.Paragraphs(1, 2).Delete
                    #End If

СТАРЫЙ КОД / больше не актуален:

Извините, это, конечно, не красиво - я новичок в VBA. Этот код прекрасно работает на windows, но выдает 6 / переполнение на Ma c. Я знаю, что могу перепрограммировать с помощью #IF Mac - но сначала мне нужно понять, ПОЧЕМУ это вызовет эту ошибку - кажется, что строка 280 может быть SectionProperties.Name, когда я пытаюсь прочитать ее в строку sSectionCollector

ОБНОВЛЕНИЕ

КОД СЕЙЧАС РАБОТАЕТ КАК ДОПОЛНИТЕЛЬНО БЕЗ ОШИБОК, НО ЭТО ПРОДУКТИРУЕТ РАЗЛИЧНЫЙ РЕЗУЛЬТАТ Windows Под Windows ок Под Ма c это как-то удваивает строки К сожалению, я не вижу / stepinto / отладки кода в надстройке в VBAEditor: - (


    Sub CreateAgendaWithSegments()
          'TODO DOCU
          'TODO Implement Button
          Dim oSl As Slide
          Dim oPl As Presentation
          Dim sAgendaCnt As Long
          Dim sAgendaTextblock As Shape
          Dim iSectIndex As Single
          Dim sSectionCollector As String
          Dim NewAgenda As Slide
          Dim AgendaLayout As CustomLayout

          'TODO reinstall ErrorHandler
10        On Error GoTo ErrorHandler

20        If ActivePresentation.SectionProperties.Count < 2 Then
30            MsgBox "You seem to have not segmented/sectioned your presentation - therefore we can not create an automated agenda slide for you -- sorry." & vbCrLf _
                  & "Consider using the SEGMENT tools first.", vbOKOnly Or vbExclamation, "No Segments"

40            GoTo Ende
50        End If
          'Collect Section Titles


          'Search for Agenda Slide
60        Set oPl = ActivePresentation
70        For Each oSl In oPl.Slides

80            If oSl.CustomLayout.Name = "AGENDA" Then

AgendaContent:
90                sAgendaCnt = sAgendaCnt + 1
100               sAgendaIndex = oSl.SlideIndex
110               oSl.Select
120               Call ExcelWork_2020.Delay(0.5)

                  'Do the magic
                  'First Reset
130               DoEvents
140               Application.CommandBars.ExecuteMso ("SlideReset")
150               DoEvents

                  'find the Textblock
160               oSl.Shapes(2).TextFrame.TextRange.Text = "Agenda"
170               Set sAgendaTextblock = oSl.Shapes(1)
180               With sAgendaTextblock.TextFrame2
190                   If .HasText Then
200                   Debug.Print sAgendaTextblock.TextFrame2.TextRange.Text

210                       Select Case MsgBox("Your agenda slide has already text. Are you sure you want to overwrite this with the new headlines from the Segmentation?", vbOKCancel Or vbExclamation, "Agenda has text")
                             Case vbCancel
220                          GoTo Ende
230                          Case vbOK
                              'Continue
240                           End Select
250                   End If 'Even if there is no text, we will write now.
                                  'Call SectionWriter
260                               With ActivePresentation.SectionProperties
270                                   For iSectIndex = 1 To .Count
280                                       sSectionCollector = sSectionCollector & vbCrLf & ActivePresentation.SectionProperties.Name(iSectIndex)
290                                   Next iSectIndex
300                               End With
310                               sAgendaTextblock.TextFrame2.TextRange.Text = sSectionCollector
320                               sAgendaTextblock.TextFrame2.TextRange.Paragraphs(1, 2).Delete
330                               GoTo Ende
                      'End If
340               End With

350           End If
360       Next oSl

          ' No Agenda found - we create one
370           Set AgendaLayout = ActivePresentation.Designs(1).SlideMaster.CustomLayouts(6)
380           Set NewAgenda = ActivePresentation.Slides.AddSlide(2, AgendaLayout)
390           Set oSl = NewAgenda


400       GoTo AgendaContent:

410       GoTo Ende

ErrorHandler:
420       MsgBox "Something went wrong -- maybe you did not select the right object for this task? If you can't find the problem, send a mail to nik@xex.one with a short description of what you tried to achieve - we will get back to you as soon as possible", vbOKOnly Or vbExclamation, "Error"

Ende:
End Sub

1 Ответ

1 голос
/ 04 мая 2020

Проблема здесь: & vbCrLf &

Это разрыв строки на Windows (Chr$(10) & Chr$(13)), но Ma c использует окончания строки Linux в стиле, и если ваш код VBA должен выполняться на обеих платформах, то самый простой способ - заменить vbCrLf на vbNewLine.

vbNewLine будет vbCrLf на Windows и vbCr на Ма c:

docs.microsoft.com

Платформа-спецификация c символ новой строки; что подходит для текущей платформы

Это то, что вызывает двойные линии на Ма c. Изменение жестко-кодированного Windows -specifi c vbCrLf на vbNewLine исправит окончания строк, решая проблему.

...