我正在创建Excel VBA脚本以通过电子邮件发送报告。在将附件包含在电子邮件中之前,我做了以下功能来验证附件。
以下功能将打开word文档,检查第一行是否与客户ID匹配并返回bool。
但是,当我从Word中读取数据时,它包含了一些隐藏的引号。
虽然两个字符串都是123a,但当我将它们粘贴到另一个文本编辑器中时,我看到我从Word中读取的字符串为" 123a"。如果我使用MsbBox打印它们,则两者都等于123a。
Function ValidateAttachment(attachmentURL As String, customerID As String) As Boolean
Dim oWord As Word.Application
Dim oWdoc As Word.Document
Set oWord = CreateObject("Word.Application")
Set oWdoc = oWord.Documents.Open(attachmentURL)
If StrComp(oWdoc.Paragraphs(1).Range.Text, customerID, vbTextCompare) = 0 Then
ValidateAttachment = True
Else
ValidateAttachment = False
End If
oWord.Quit
Set oWord = Nothing
Exit Function
End Function
当我将两个结果写入常规单元格时,这就是我所看到的。即使我制作一个简单的公式IF来检查是否平等,它也不起作用。
答案 0 :(得分:0)
尝试:
If StrComp(Replace(oWdoc.Paragraphs(1).Range.Text,chr(34),""), customerID, vbTextCompare) = 0 Then
答案 1 :(得分:0)
我找到了如何处理隐形引号。
使用它可以解决问题:
Application.WorksheetFunction.Clean()
这是最终的代码:
Function ValidateAttachment(attachmentURL As String, customerID As String) As Boolean
Dim oWord As Word.Application
Dim oWdoc As Word.Document
Set oWord = CreateObject("Word.Application")
Set oWdoc = oWord.Documents.Open(attachmentURL)
Dim x As String
x = "123a"
Application.Sheets(1).Columns(3).Rows(2) = Replace(oWdoc.Paragraphs(1).Range.Text, Chr(34), "")
If StrComp(Application.WorksheetFunction.Clean(oWdoc.Paragraphs(1).Range.Text), customerID, vbTextCompare) = 0 Then
ValidateAttachment = True
Else
ValidateAttachment = False
End If
oWord.Quit
Set oWord = Nothing
Exit Function
End Function