【问题标题】:Comparing the first paragraph of two documents比较两个文档的第一段
【发布时间】:2022-12-11 07:53:02
【问题描述】:

我正在尝试比较内容相同的两个文件的第一段。一种是活动文件,一种是指定的“参考文件”。

我用来存储内容的两个范围不断出现不相等,即使使用 Documents.Compare 检查这两个文件没有差异。

在我逐步检查变量时,两个范围的内容在比较时似乎是相同的。

为不一致的变量命名方案道歉。

Sub Test_Comparison()

Dim WorkingDoc As Document
Dim formatRef As Document

Dim rngDoc As Range
Dim refRnge As Range

Dim MacroViable As Boolean

Set WorkingDoc = Documents(ActiveDocument)
Set formatRef = Application.Documents.Open("[Reference FilePath]\ReferenceFile.docx", ReadOnly:=True, Visible:=False)

Set rngDoc = Documents(WorkingDoc).Paragraphs(1).Range
Set refRange = formatRef.Paragraphs(1).Range

If rngDoc.IsEqual(Range:=refRange) Then 'This is the bit not working.  The contents of the variables seems identical. What gives??
    MacroViable = True
End If

Documents("ReferenceFile.docx").Close

End Sub

我还尝试将两个范围设置为相等:

If refRange = rngDoc Then 
    MacroViable = True
End If

【问题讨论】:

  • 比较前两段的文本很容易,但要测试它们的格式是否相同则需要做更多的工作。 Word 的内置文档比较工具非常适合这种情况。不需要 VBA。他们还将识别整个文档中的其他差异。

标签: vba ms-word comparison paragraph


【解决方案1】:

您可以比较范围,但它们不会相等 - 因为它们是不同文档的一部分(例如“IsEqual”的帮助:https://learn.microsoft.com/en-us/office/vba/api/word.range.isequal

您必须比较两个范围的 text

If rngDoc.Text = refRange.Text Then
   MacroViable = True
End If

【讨论】:

    猜你喜欢
    • 2019-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多