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

 

 

 

 

  

 

相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页