当前位置:首页经验技巧Word经验word文档

如何在Excel VBA 中读写word文档 步骤

2024-07-18 10:22:20

1.如何在Excel VBA 中读写word文档 步骤

所以需要先引入word库,操作步骤如下:

1.1 打开excel vba 界面

1.2 选中其中的一个Module

1.3 选择菜单, Tools --> References

在打开的对话框中选择类似 "Microsoft Word 14.0 Object Library".

1.4 点击OK保存配置。

2. 打开文档

Set wordApplication = CreateObject("Word.Application")

wordApplication.Visible = False

Dim hasOpenDoc As Boolean

hasOpenDoc = IsOpen(filePath) ' is a self-defined function to check file is opend

If hasOpenDoc = True then

Set wordDoc = GetObject(filePath)

End if

If hasOpenDoc = False Then

Set wordDoc = wordApplication.Documents.Open(filePath)

End if

wordDoc.Active

With wordApplication

Dim aParagraph As Word.Paragraph

For Each aParagraph In wordDoc.Paragraphs

' do some thing to every paragraph.

Next aParagraph

End with

wordDoc.Close

Set wordDoc = nothing

' 如下这段代码引用某位牛人的,非常感谢他。由于路径丢失,不能给出链接, 抱歉

' 如下的找寻方式,能够正确的找出文件是否被打开

Function IsOpen(fileName As String) As Boolean

IsOpen = False

Dim findFile As Integer

findFile = FreeFile()

On Error GoTo ErrOpen

Open fileName For Binary Lock Read Write As findFile

Close findFile

Exit Function

ErrOpen:

If Err.Number <> 70 Then

Msg = "Error # " & Str(Err.Number) & "was generated by " & Err.Source & Chr(13) & Err.Description

MsgBox Msg, "Error", Err.HelpFile, Err.HelpContext

Else

IsOpen = True

End If

End Function

2.word如何使用vba

1、在Word中打开你需要处理的doc文档; 2、键入ALT+F11; 3、在出现的VBA窗口中,粘贴你下载的代码; 4、把键盘光标放到入口函数中任意一行代码上(如果你不知道是什么地方,可以把代码贴上来看看); 5、键入F5运行; 6、切换回doc文档窗口看效果。

补充: 哦,可能是因为你目前还没有任何宏所以才看到这样的灰色一片。 那就这样,现在左边的工程里面有个“Normal”吧?展开它后有个“模块”节点吧?在这个“模块”节点上点鼠标右键,选择“插入-模块”。

这样右边就会出现代码窗口了。然后再按照上面步骤3-6。

如果还不清楚可以继续补充提问或发我信息。

3.关于Word中 的VBA 编程

解决你的“顺便问下"。..

Sub Macro1()

Dim strText As String

strText = "建立反对撒客里空的龙卷风"

Selection.TypeText strText

Selection.MoveStart Unit:=wdLine, Count:=-1

Selection.MoveEnd Unit:=wdCharacter, Count:=-1 * (Len(Selection.Text) - 4)

Selection.MoveStart Unit:=wdCharacter, Count:=3

Selection.Font.Bold = True

MsgBox Selection.Text

End Sub


电脑版

免责声明:本站信息来自网络收集及网友投稿,仅供参考,如果有错误请反馈给我们更正,对文中内容的真实性和完整性本站不提供任何保证,不承但任何责任,谢谢您的合作。
版权所有:五学知识网 Copyright © 2015-2024 All Rights Reserved .