将单词内容存储在变量中 [英] store word content in variable

查看:40
本文介绍了将单词内容存储在变量中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 VBA 中复制 Word 文档的全部内容(约 2 页)并存储在变量中?

How do I copy the entire content (approx 2 pages) of a Word document in VBA and store in a variable?

我一直在尝试几种方法,但都不起作用:

I keep trying several things, none of which works:

Dim mainData As String
ThisDocument.Activate
ActiveDocument.WholeStory 'error on this line
mainData = Selection.Text

使用记录宏",我可以模拟选择一段或整个文本,但我无法模拟将其存储到变量中.

With 'record macro' I can simulate selecting a piece or the entire text, but I can't simulate storing that into a variable.

上面的代码抛出

'此命令不可用,因为没有打开文档',

'This command is not available because no document is open',

但是我不是首先激活了这个(当前)文档,然后选择了它(ActiveDocument.WholeStory)吗?为什么这不起作用?

but hadn't I first activated this (the current) document, and then selected it (ActiveDocument.WholeStory)? Why doesn't this work?

后期我设法做这样的选择:

Dim sText As String
Application.Selection.ClearFormatting
Application.Selection.WholeStory
sText = Application.Selection.Text
MsgBox sText

但问题是我无法将整个文本(2 页)存储在变量中.它的一部分被截断了.你知道如何逐词存储吗(反正我一次只需要一个词)?

but the problem is I can't store the entire text (2 pages) in a variable. Part of it is truncated. Would you know how to store word by word (I only need a word at a time anyway)?

稍后编辑.我在文本上应用了 strReverse 以发现文本实际上完全存储在变量中,只是没有完全显示在消息框中.

Later edit. I applied strReverse on the text to find out the text is actually stored entirely in the variable, just not fully displayed in the message box.

推荐答案

不要在代码中使用 ThisDocument ,除非您特别想要处理存储和运行代码的文件.ThisDocument 是该文件的代码名称".

Don't use ThisDocument in code, unless you specifically want to address the file in which the code is stored and running. ThisDocument is the "code name" of that file.

相反,使用 ActiveDocument 表示 Word 窗口中当前处于活动状态的文档.

Instead, use ActiveDocument to mean the document currently active in the Word window.

另外,如果您想要当前活动文档中的选择,没有理由激活它 - 它已经处于活动状态.

An addition, if you want the Selection in the currently active document, there's no reason to activate it - it's already active.

所以要在一个字符串中获取整个文档内容

So to get the entire document content in a string

Dim mainData As String
mainData = ActiveDocument.Content.Text

其中 Content 将整个主体的文本作为 Range 对象返回.

where Content returns the entire main body's text as a Range object.

注意:MsgBox 有字符上限.如果您正在处理长文本字符串并想查看它们包含的内容,则以下内容具有更多(但不是无限")容量:

Note: The MsgBox has an upper character limit. If you're working with long text strings and want to see what they hold the following has more (but not "infinite") capacity:

Debug.Print mainData

这篇关于将单词内容存储在变量中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆