開啟一個Word檔案並修改它
大家好,今日推出常用“積木”過程案例分享第316期,今日內容是開啟一個Word檔案並修改它。VBA是利用Office實現個人小型辦公自動化的有效手段(工具)。我推出的專輯中這些資料就是我多年經驗的記錄,都來源於我多年的實踐經驗的記錄。大家要把這些程式碼塊作為一塊塊的積木對待,平時要多積累,建立自己的“積木庫”,用時拿來可以修正、組合。這就是我的“積木程式設計”的思想,程式碼不要自己全部的錄入。這些講解就是我推出的“積木”方案,希望大家加以利用。最近程式碼多是出自我的第六套教程”VBA資訊獲取與處理”。這是非常實用的實際問題解決方案。
=========================== ① =========================
Sub MYNZB()
Dim RR As Boolean
Dim myWdA As Object
Dim MyDocument As Object
RR = WordIsOpen(ThisWorkbook。Path & “\001 在WORD中啟用EXCEL。docm”)
If Not RR Then
Set myWdA = CreateObject(“Word。Application”)
myWdA。Visible = True
Set MyDocument = myWdA。Documents。Open(ThisWorkbook。Path & “\001 在WORD中啟用EXCEL。docm”)
mystr = ThisWorkbook。Sheets(2)。Cells(2, 3)。Value
MyDocument。Tables(1)。Cell(2, 3)。Range。Text = mystr
MyDocument。Save
Set myWdA = Nothing
Set MyDocument = Nothing
Else
Set myWdA = GetObject(, “WORD。Application”)
For Each doc In myWdA。Documents
UU = UCase(doc。FullName)
If doc。FullName = ThisWorkbook。Path & “\001 在WORD中啟用EXCEL。docm” Then
mystr = ThisWorkbook。Sheets(2)。Cells(2, 3)。Value
doc。Tables(1)。Cell(2, 3)。Range。Text = mystr
doc。Save
Set doc = Nothing
Exit For
End If
Next
Set myWdA = Nothing
End If
End Sub
=========================②========================
程式碼講解:
① If Not RR Then ‘建立Word物件
Set myWdA = CreateObject(“Word。Application”)
myWdA。Visible = True ’開啟指定文件
Set MyDocument = myWdA。Documents。Open(ThisWorkbook。Path & “\001 在WORD中啟用EXCEL。docm”)
‘獲取當前Excel的SHEET2的單元格C2資料
mystr = ThisWorkbook。Sheets(2)。Cells(2, 3)。Value
’將取得得值設定到Word表格的1行2列中
MyDocument。Tables(1)。Cell(2, 3)。Range。Text = mystr
MyDocument。Save
Set myWdA = Nothing
Set MyDocument = Nothing
上述程式碼是開啟檔案及修正檔案的程式碼。
② Set myWdA = GetObject(, “WORD。Application”)
For Each doc In myWdA。Documents
UU = UCase(doc。FullName)
If doc。FullName = ThisWorkbook。Path & “\001 在WORD中啟用EXCEL。docm” Then
mystr = ThisWorkbook。Sheets(2)。Cells(2, 3)。Value
‘將取得的值設定到Word表格的1行2列中
doc。Tables(1)。Cell(2, 3)。Range。Text = mystr
doc。Save
Set doc = Nothing
Exit For
End If
Next
Set myWdA = Nothing
上述程式碼是當檔案已經開啟,定位所給出的檔案,然後修訂檔案的程式碼。
各套教程的介紹:
第1套:VBA程式碼解決方案
第2套:VBA資料庫解決方案
第3套:VBA陣列與字典解決方案
第4套:VBA程式碼解決方案之影片
第5套:VBA中類的解讀和利用
第6套:VBA資訊獲取與處理
上述教程的學習順序:1→3→2→6→5或者4→3→2→6→5。
分享成果,隨喜正能量