相關文章:
【VBA範例】:如何在Excel中操控MS Word
【VBA範例】:含有合併欄之Excel檔案如何排序
VBA的功能相當完備,可以由一個微軟程式來控制另一個微軟程式,例如它可以讓Excel控制Word,也可以讓Word控制Excel.今天先介紹如何由Word來控制Excel.
因為Excel並無計算字數的功能,所以想要計算字數時,只好借重Word.下面這個例子是先將要計算字數的那些格子貼到Word,Word算了字數後,會將結果直接輸到Excel.
====================
Option Explicit
'本程式計算每一段之字數,
'然後將結果存於Excel檔案中
'
'使用方法
'一、將要計算之格子由Excel(file1.xlsm)貼到Word(test.docx)裡
'二、執行本程式
'假設:file1.xlsm之第四行用以儲存字數,第六行之第一、二格儲存時間,
'以計算程式執行時間.
'
'
'使用前要先選用Excel Object Library.方法如下:
' 在Word裡,先進入VBA(Word 2007:developer/VB)然後選 Tools/References……接著勾選
'Microsoft Excel x.x Object Library.我的 x.x 是 12.0)
Sub count_words_table()
Dim oWdRange As Word.Range
Dim iTotalWords1 As Integer
Dim iTotalWords2 As Integer
Dim iLoop As Integer
Dim n As Integer
Dim oRow As Row
Dim oXL As Excel.Application
Dim oWB As Excel.Workbook
Dim oRng As Excel.Range
Dim ExcelWasNotRunning As Boolean
Dim WorkbookToWorkOn As String
Application.ScreenUpdating = False
'指定所要使用之 Excel 檔案名稱
WorkbookToWorkOn = "C:\Documents and Settings\me\My Documents\file1.xlsm"
Windows("test.docx").Activate
'隱藏視窗,執行速度較快
Application.Visible = False
'If Excel is running, get a handle on it; otherwise start a new instance of Excel
On Error Resume Next
Set oXL = GetObject(, "Excel.Application")
If Err Then
ExcelWasNotRunning = True
Set oXL = New Excel.Application
End If
On Error GoTo Err_Handler
'打開 Excel 檔案
Set oWB = oXL.Workbooks.Open(FileName:=WorkbookToWorkOn)
oWB.Application.ScreenUpdating = False
'儲存程式開始執行的時間,用以計算本程式執行時間
oXL.ActiveWorkbook.Worksheets("綜合").Cells(1, 6).Value = Now()
'計算總共執行次數,一段一次
iLoop = ActiveDocument.ComputeStatistics(wdStatisticParagraphs)
For n = 1 To iLoop
'先算總共的字數
iTotalWords1 = ActiveDocument.ComputeStatistics(wdStatisticWords)
'選取第一段,刪去,再算字數.二者之差即第一段之字數
Set oWdRange = ActiveDocument.Paragraphs(1).Range
oWdRange.Delete
iTotalWords2 = ActiveDocument.ComputeStatistics(wdStatisticWords)
'直接將結果儲存到 Excel 檔中
oXL.ActiveWorkbook.Worksheets("sheet1").Cells(n, 4).Value = iTotalWords1 - iTotalWords2
Next n
'儲存程式結束的時間
oXL.ActiveWorkbook.Worksheets("綜合").Cells(2, 6).Value = Now()
oWB.Save
oWB.Close False
'quit
If ExcelWasNotRunning Then
oXL.Quit
End If
'Make sure you release object references.
Set oWB = Nothing
Set oXL = Nothing
Application.ScreenUpdating = True
Application.Visible = True
Exit Sub
Err_Handler:
MsgBox WorkbookToWorkOn & " caused a problem. " & Err.Description, vbCritical, _
"Error: " & Err.Number
If ExcelWasNotRunning Then
oXL.Quit
End If
End Sub