VBA 读取 CR/LF 个字符时 PPT 错误

VBA PPT error while reading CR/LF character

我在为 Ppt 文档编写 VBA 宏时遇到了一个奇怪的问题。 在代码中,我想在演示文稿的每张幻灯片的最顶部提取框架中的文本。 文本按换行符划分,所以首先我想搜索换行符。 我正在使用 Instr 函数来搜索字符串中换行符的位置。 代码如下:

Sub SetTitle()
Dim sl As Slide
Dim sh As Shape
Dim trng As TextRange
Dim asptext() As Variant

For Each sl In ActivePresentation.Slides
    For Each sh In sl.Shapes
        If sh.Top = 5.403701 Then
            Set trng = sh.TextFrame.TextRange
            txt = trng.Text
            Debug.Print txt
            pos = InStr(1, Chr(13), txt)
            Debug.Print pos
            Debug.Print Asc(Mid(txt, 7, 1))
            If pos <> 0 Then
                Debug.Print pos
            End If
        End If
    Next sh
Next sl

End Sub

立即 window 我得到以下结果:https://i.stack.imgur.com/Ig41i.png

调试器报错:

Runtime error '5': Invalid procedure call or argument

换行

Debug.Print Asc(Mid(txt, 7, 1))

所以我认为这个NL字符的识别有问题。 你知道为什么会这样吗?

错误可能不是来自任何换行符,而是来自太短的字符串。 Mid(txt, 7, 1) 将 return 一个空字符串,这不是 Asc 函数的有效参数。

要检查换行符,您可以使用常量 vbCr(与 Chr(13) 相同)和 vbLf(与 Chr(10) 相同)和 vbCrLf.

如果您不确定字符串的内容,可以使用以下函数:

Function DumpString(s As String) As String
    Const Separator = ", "
    
    ' Write all chars of String as ASCII-Value
    Dim i As Long
    For i = 1 To Len(s)

        Dim a As Long, c As String
        a = AscW(Mid(s, i, 1))
        
        If a = AscW(vbCr) Then
            c = "<CR>"
        ElseIf a = AscW(vbLf) Then
            c = "<LF>"
        ElseIf a = AscW(vbTab) Then
            c = "<TAB>"
        ElseIf a = 0 Then
            c = "<NUL>"
        Else
            c = Mid(s, i, 1)
        End If
        
        DumpString = DumpString & IIf(DumpString = "", "", Separator) & a & "(" & c & ")"
    Next i
End Function