[英]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 我收到消息
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
您可以使用
.Find
和Replace
,而不是遍历单元格并替换文本。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.