http://www.techrepublic.com/blog/msoffice/how-to-automatically-execute-a-word-macro-when-you-create-open-or-close-a-document/4770
http://60-251-1-52.hinet-ip.hinet.net/taiwan/msdn/library/2003/Jun-2003/odc_wdappevnt.htm
http://office.microsoft.com/en-us/project-help/add-a-digital-signature-to-a-file-or-macro-project-HP005249557.aspx
http://stackoverflow.com/questions/5651890/using-vba-to-get-extended-file-attributes
http://www.java2s.com/Code/VBA-Excel-Access-Word/Access/Connectionerrorhandler.htm
http://p2p.wrox.com/excel-vba/39128-adodb-connection-user-defined-type-not-defined.html
http://windowssecrets.com/forums/showthread.php/117906-Query-Access-from-Word-VBA
http://kimbalko-chi.blogspot.tw/2010/06/how-toexcel-vba-sql.html
http://civil.njtc.edu.tw/weng/excel/lectureNote/1.6.htm
目的:
開啟 Office 檔案時執行 VBA 檢查文件是否有新版。
架構:
- 在檔案的資訊欄位紀錄文件版本
- 將最新的版本號碼紀錄在 Excel 檔 (放在網路磁碟機)
- 在 Office 檔案增加 VBA script 檢查文件版本是否符合 Excel 檔裡面的紀錄
將最新的版本號碼紀錄在 Excel 檔 (放在網路磁碟機):
EX: Excel 檔是 P:\temp\last_version.xlsx
在 Office 檔案增加 VBA script 檢查文件版本是否符合 Excel 檔裡面的紀錄:
- 開啟 Word 檔案,用 Alt + F11 叫出 Visual Basic Editor
- Double click "ThisDocument", 選擇 "Document" and "Open"
- VBA 程式內容
Private Sub Document_Open()
Dim str_comment As String
str_comment = ThisDocument.BuiltInDocumentProperties("Comments")
ConnectDB (str_comment)
End Sub
Sub ConnectDB(str_comment)
Dim conn As ADODB.Connection
Dim strSQL As String
Dim rs As ADODB.Recordset
Set conn = New ADODB.Connection
conn.Provider = "Microsoft.ACE.OLEDB.12.0"
conn.ConnectionString = "Data Source=P:\Temp\last_version.xlsx; Extended Properties=Excel 12.0;"
On Error GoTo Except
conn.Open
strSQL = "Select * FROM [Version$] where version_number = '" & str_comment & "'"
Set rs = New ADODB.Recordset
rs.CursorLocation = adUseClient
rs.Open strSQL, conn
If rs.RecordCount = 0 Then
'MsgBox rs.Fields("version_number").Value
MsgBox "文件版本已更新,請到 Portal 下載新版。"
End If
Except:
Dim ADOError As ADODB.Error
For Each ADOError In conn.Errors
MsgBox "請和系統管理員連絡。 ADO Error: " & ADOError.Description & " Native Error: " & _
ADOError.NativeError & " SQL State: " & _
ADOError.SQLState & "Source: " & _
ADOError.Source, vbCritical, "Error Number: " & ADOError.Number
Next ADOError
End Sub
- 新增 Object Reference for Excel opening。從 Tools / References 新增 Microsoft ActiveX Data objects 2.x Library, Microsoft ActiveX Data objects Recirdset 2.x Library
- 製作可以對 VBA 簽章的憑證。
- 將這個憑證用 Group policy 發佈到 domain。
- 用憑證對 VBA 簽數位簽章,這樣開啟檔案時 VBA 才不會被擋住。
- 存檔時選擇 Word Macro-Enabled Document (*.docm)
2013/9/25 update
如果要用ReadOnly開啟Excel檔,請加上紅色的部分。
conn.ConnectionString = "Data Source=P:\Temp\last_version.xlsx; Extended Properties=Excel 12.0; Mode=Read;"
Reference: http://www.vb-helper.com/howto_ado_read_only_db.html
Reference: http://www.vb-helper.com/howto_ado_read_only_db.html
沒有留言:
張貼留言