使用VBA检查Word 2016中的空文本框

问题描述 投票:0回答:1

我在Word 2016文档中有一个文本框。这不是TextBox表单对象,而是从“插入”选项卡插入的普通文本框:

Insert Menu

我打算在打开文档时检查它是否为空。对于我的生活,我无法弄清楚如何做到这一点。我尝试了以下所有方法:

If (Len(ActiveDocument.Sections(1).Headers(wdHeaderFooterPrimary).Shapes("Text Box 2").TextFrame.TextRange.Text & vbNullString) = 0) Then
If (IsNull(ActiveDocument.Sections(1).Headers(wdHeaderFooterPrimary).Shapes("Text Box 2").TextFrame.TextRange.Text)) Then
If (LTrim(RTrim(ActiveDocument.Sections(1).Headers(wdHeaderFooterPrimary).Shapes("Text Box 2").TextFrame.TextRange.Text)) = "") Then
If (ActiveDocument.Sections(1).Headers(wdHeaderFooterPrimary).Shapes("Text Box 2").TextFrame.TextRange.Text = "") Then

当文本框为空时,这些都不会返回true?这是文本框:

Text Box

似乎文本框始终包含段落标记(我无法删除)。这是VBA手表显示的内容:

Watch :   : ActiveDocument.Sections(1).Headers(wdHeaderFooterPrimary).Shapes("Text Box 2").TextFrame.TextRange.Text : "
" : String : ThisDocument.Document_Open

请注意,手表是两条独立的线条,这让我觉得那里有CRLF或其他东西?

vba ms-word word-vba
1个回答
1
投票

在一个空的文本框中总是有一个段落。因此,您可以使用以下内容:

Private Sub Document_Open()
  With ActiveDocument.Sections(1).Headers(wdHeaderFooterPrimary).Shapes("Text Box 2")
    If Not .TextFrame Is Nothing Then
      If Trim(.TextFrame.TextRange.Text) = vbCr Then
        MsgBox "Empty Text Range"
      End If
    Else
      MsgBox "No Text Range"
    End If
  End With
End Sub
© www.soinside.com 2019 - 2024. All rights reserved.