简体   繁体   English

如何在VBA宏中以读写更多方式打开Word文档并将Text写入Document中?

[英]How do I open a word document via VBA macro in read write more and write Text into the Document?

I am getting the Message 我收到消息

  1. Open Read only 打开只读
  2. Local Copy 本地副本
  3. Recieve Notification when available I need to open the doc in the read write mode, and the document is closed before the macro is executed 接收通知(如果可用),我需要以读写模式打开文档,并且在执行宏之前关闭文档

Also I ahve doubts on the way I am writing the Text 我也对我编写文本的方式有疑问

Sub Read_Write_Document()

  Dim p As Long, r As Long
  Set wrdApp = CreateObject("Word.Application")

  wrdApp.Visible = True

  Set wrdDoc = wrdApp.Documents.Open("C:\Documents and Settings\Desktop\Word_File_read_write_1.docx")

  Dim i As Integer
  i = 1
  With wrdDoc_Read
      For p = 1 To .Paragraphs.Count
          Set tRange = .Range(Start:=.Paragraphs(p).Range.Start, End:=.Paragraphs(p).Range.End)
           tString = tRange.Text
           tString = Left(tString, Len(tString) - 1)

           If InStr(1, tString, "1") > 0 Then
              If Mid(tString, 1, 4) = "date" Then 
                  tRange.Text = "DATE" ' Write Text
              End If
          End If
      Next p
  End With
  .SaveAs ("C:\Documents and Settings\Desktop\Word_File_read_write_2.docx") 
  wrdApp.Quit ' close the Word application
  Set wrdDoc = Nothing
  Set wrdApp = Nothing

End Sub

Couple of things 几件事

A 一种

It's always advisable to use Option Explicit 始终建议使用Option Explicit

You have declared the word document as wrdDoc but are using wrdDoc_Read 您已将单词document声明为wrdDoc但是正在使用wrdDoc_Read

Change the line 换线

With wrdDoc_Read

to

With wrdDoc

B

Next your .SaveAs routine is outside the With - End With and hence will give you error 接下来,您的.SaveAs例程在With - End With ,因此会给您错误

C C

You are directly quitting the word application without closing the word document. 您将直接退出Word应用程序,而无需关闭Word文档。 It's always good to issue a wrdDoc.Close (False) after a .SaveAs because there are instances where an installed add-in can make changes to your document and quitting the word application will prompt the .SaveAs again. .SaveAs之后发出wrdDoc.Close (False)总是很好,因为在某些情况下,已安装的加载项可以对文档进行更改,并且退出单词application会再次提示.SaveAs

D d

Instead of looping through the cells and replacing the text, you can use .Find and Replace 您可以使用.FindReplace ,而不是遍历单元格并替换文本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM