从excel打开word doc,在同一页面上打印选择和字符串

时间:2016-12-13 07:55:30

标签: excel-vba vba excel

我有一个带有文档的数据库。文件名类似于000001,000002 ......

我已经成功编写了一个打开这些文档的宏,在找到值之前进行选择,打印此选择,然后再次关闭文档并继续下一步。 (见下面的代码)

有一件事我想做多余的事,但我无法弄清楚。我希望在此选项下打印“结束”一词(在同一页面上)。但我想在不对文件进行任何更改的情况下这样做。 enter image description here

我不想更改文档,因为需要使用选择打印的值来自userform文本框,并且每次都不同。但如果有人可以帮助我,你可以举一个例子结尾

在我正在寻找的内容中添加了一张图片

现在这是我的代码:

Dim i As Long, wdApp As Object, wdDoc As Object, wdRng As Object
Set wdApp = CreateObject("Word.Application")
With wdApp
  .Visible = True
  For i = 1 To 9
    Set wdDoc = .Documents.Open("\\path\" & Format(i, "000000") & ".NET", False, True, False)
With wdDoc
  Set wdRng = .Range(0, 0)
  With .Range
    With .Find
      .Text = "ENDLIST"
      .Forward = True
      .MatchWholeWord = True
      .MatchCase = True
      .Execute
    End With
    If .Find.found = True Then
      wdRng.End = .Duplicate.Start
      wdRng.Select
      wdDoc.PrintOut , Range:=1
    End If
  End With
  .Close False
End With
  Next
  .Quit
End With
Set wdRng = Nothing: Set wdDoc = Nothing: Set wdApp = Nothing

End Sub

这是可能的吗?如果可以,有人可以帮我走吧

1 个答案:

答案 0 :(得分:0)

自己找到它。下面的代码将打开word文件,将在文档开头添加信息,从头开始选择,直到找到一个单词,打印此选择,然后再次关闭word文件。

在选择之后无法弄清楚如何获得它,如问题图片所示。但只要纸上所需的信息显而易见,这个地方并不重要。

Sub test()


Dim i As Long, wdApp As Object, wdDoc As Object, wdRng As Object, wRng As Object
Dim BEGINNING_OF_STORY
Dim MOVE_SELECTION

BEGINNING_OF_STORY = 6

MOVE_SELECTION = 0

Set wdApp = CreateObject("Word.Application")
With wdApp
  .Visible = True
  For i = 1 To 2
    Set wdDoc = .Documents.Open("M:\" & Format(i, "000") & ".docx")
    With .Selection
    .Font.Bold = True
    .HomeKey BEGINNING_OF_STORY, MOVE_SELECTION
    .Font.Size = "25"
    .TypeText ("information" & vbCrLf)
    End With
    With wdDoc
      Set wdRng = .Range(0, 0)
      With .Range
        With .Find
          .Text = "DEF"
          .Forward = True
          .MatchWholeWord = True
          .MatchCase = True
          .Execute
        End With
        If .Find.found = True Then
          wdRng.End = .Duplicate.Start
          wdRng.Select
          wdDoc.PrintOut , Range:=1
        End If
      End With
      .Close False
    End With
  Next
  .Quit
End With
Set wdRng = Nothing: Set wdDoc = Nothing: Set wdApp = Nothing

End Sub

满足我自己的需求,希望其他人有时也可以使用它