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.ActiveWith wordApplication Dim aParagraph As Word.Paragraph For Each aParagraph In wordDoc.Paragraphs " do some thing to every paragraph. Next aParagraphEnd withwordDoc.CloseSet 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 FunctionErrOpen: 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 IfEnd Function
所以需要先引入word庫,操作步驟如下:
1.1 開啟excel vba 介面1.2 選中其中的一個Module1.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.ActiveWith wordApplication Dim aParagraph As Word.Paragraph For Each aParagraph In wordDoc.Paragraphs " do some thing to every paragraph. Next aParagraphEnd withwordDoc.CloseSet 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 FunctionErrOpen: 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 IfEnd Function