说明1. 用 ActiveWorkbook.Path 取得 Excel 活页簿的所在资料夹
2. Excel 2010 要用副档名 xlsm 储存才能存 Macros (程式码)
3. 开启 Word 先用 instances = OpenWord() 返回 Word 的实体,操作完后用 CloseWord(instances) 关闭
4. 程式码需要先加入参考 Microsoft Word XXX Object Library,如果用 2010 版 XXX 是 14.0
5. 底下程式码开启和 Excel 同资料夹的 Word 文件名称 "Document1.docx"
6. 程式码如和测试如附件所示,请将 test 资料夹放到 "C:\test\" 进行测试
图片▼ 如何执行 Macro
▼ Document1.docx 内容
▼ 执行 TestOpenWord() 结果
如果执行 TestGetCurrentWorkingDirectory() 你应该会看到 "C:\test\"
程式码复制程式
Option Explicit
' Test getting current working directory and opening word files.
'
' Note: Add the following references:
' Microsoft Word XXX Object Library
'
' Author: Shawn Chang
' Tested on Excel 2010 and Word 2010
Private Type WordInstances
wordApp As Word.Application
wordDoc As Word.Document
End Type
Public Sub TestGetCurrentWorkingDirectory()
MsgBox GetCurrentWorkingDirectory()
End Sub
Public Sub TestOpenWord()
' Open word instances by document path
Dim documentPath As String
Dim instances As WordInstances
documentPath = GetCurrentWorkingDirectory() & "\Document1.docx"
instances = OpenWord(documentPath)
' Get first paragraph text
Dim firstParagraphText As String
firstParagraphText = GetWordParagraphText(instances.wordDoc, 1)
' Show first paragraph text
MsgBox firstParagraphText
' Close word instances
CloseWord instances
End Sub
Private Function GetCurrentWorkingDirectory() As String
GetCurrentWorkingDirectory = ActiveWorkbook.Path
End Function
Private Function GetWordParagraphText(doc As Word.Document, paragraphIndex As Integer) As String
Dim docParagraph As Word.Paragraph
Set docParagraph = doc.Paragraphs(paragraphIndex)
GetWordParagraphText = docParagraph.Range.Text
End Function
Private Function OpenWord(docPath As String) As WordInstances
Dim instances As WordInstances
With instances
Set .wordApp = CreateObject("Word.Application")
Set .wordDoc = GetObject(docPath)
End With
OpenWord = instances
End Function
Private Sub CloseWord(instances As WordInstances)
With instances
.wordDoc.Close
.wordApp.Quit
Set .wordApp = Nothing
Set .wordDoc = Nothing
End With
End Sub
参考How to use Automation with Word 2002