首页 > 解决方案 > 为什么我的 vba 代码返回占位符文本

问题描述

我是 VBA 和 word 宏的新手,所以请多多包涵。我创建了一个简单的表单,现在我只想在发送电子邮件之前对按钮进行一些验证。

我这里有一些代码。

Private Sub CommandButton1_Click()

   Dim errors As String

   errors = ""

   Dim strText As String
   strText = ActiveDocument.SelectContentControlsByTitle("MyField")(1).Range.Text

   errors = strText //debugging line - remove if required

   If strText = "" Then
        If errors = "" Then
            errors = "MyField Blank"
        Else
            errors = errors & vbNewLine & "Practise Name Blank"
        End If

   End If



   If errors = "" Then
        Options.SendMailAttach = True
        ActiveDocument.SendMail
   Else
        MsgBox "Please Correct Then Following Errors" & vbNewLine & errors
   End If

End Sub

它附加到一个按钮,但 strText 正在返回占位符文本。你如何阻止这种情况发生?

我正在使用新版本的单词表单控件。

标签: vbams-word

解决方案


鉴于您写的内容,我的方法是检查占位符文本并将内容控件的内容与之进行比较。如果它们相同,就好像内容控件没有内容一样。

请注意,我不确定最后一个IF-block 的意图是什么,因为在给定前面的代码的情况下,errors它不能是空(零长度)字符串 - 它总是包含一些东西,基于前面的If-block。但也许这是由于测试占位符的问题......

  Dim errors As String, ph As String
  Dim cc As Word.ContentControl

   errors = ""

   Dim strText As String
   Set cc = ActiveDocument.SelectContentControlsByTitle("MyField")(1)
   ph = cc.PlaceholderText
   strText = cc.Range.Text

   errors = strText

   If strText = "" Or strText = ph Then
        If errors = "" Or strText = ph Then
            errors = "MyField Blank"
        Else
            errors = errors & vbNewLine & "Practise Name Blank"
        End If

   End If

   If errors = "" Then
        Options.SendMailAttach = True
        ActiveDocument.SendMail
   Else
        MsgBox "Please Correct Then Following Errors" & vbNewLine & errors
   End If

推荐阅读