从 Excel VBA 写入 Word 文档时无法使用“Selection.TypeText”方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21564791/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-12 01:44:25  来源:igfitidea点击:

Can't use 'Selection.TypeText' method when writing to Word document from Excel VBA

excelvbaexcel-vbams-word

提问by Srlle

I'm trying to write to a Word document from Excel VBA, and when I try using .TypeTextmethod on Selectionobject, I get an error: "Object doesn't support this property or method."

我正在尝试从 Excel VBA 写入 Word 文档,当我尝试.TypeTextSelection对象上使用方法时,出现错误:“对象不支持此属性或方法。”

I've read somewhere that Excel VBA doesn't know that I'm referring to the Selection object in my Word document, so I tried the suggested solution, which was to try to do it in a With- End Withblock.

我在某处读到 Excel VBA 不知道我指的是 Word 文档中的 Selection 对象,因此我尝试了建议的解决方案,即尝试在With-End With块中执行此操作。

Basically I tried this:

基本上我试过这个:

Set WrdApp = New Word.Application
Set DestDoc = WrdApp.Documents.Add
With DestDoc
   .Activate
   .Select
   .Selection.TypeText Text:="Test"
End With    

But it always reports the same error on the .Selection.TypeTextline.

但是总是报同样的错误就.Selection.TypeText行了。

Any help would be appreciated.

任何帮助,将不胜感激。

采纳答案by Jerome Montino

Try this:

尝试这个:

Sub WriteToWord()

Dim WrdApp As New Word.Application
Dim WrdDoc As Document
Dim WrdSel As Selection

WrdApp.Visible = True
Set WrdDoc = WrdApp.Documents.Add
Set WrdSel = WrdApp.Selection

WrdSel.TypeText "Test"

End Sub

You were pretty close with your code. The error you were having is that there is no .Selectionproperty for DestDoc. You could have done it outside instead. However, your style is not best practice, so refer to my style above so you can identify exactly which is what. :)

你很接近你的代码。您遇到的错误是,没有任何.Selection财产DestDoc。你本来可以在外面做的。但是,您的风格不是最佳实践,因此请参考我上面的风格,以便您可以准确确定哪个是什么。:)

Let is know if this helps.

让我们知道这是否有帮助。