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

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

问题描述

如何在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?

稍后我设法做到了这样的选择:

Later edit: I managed to do the selection like this:

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

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

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