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

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

 

 

 

 

  

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值