我被提出一個謎題。我工作的地方有大量的Word模板,它們都包含一個包含一些錯誤的autonew事件句柄。這個錯誤在所有模板中。我想知道是否可能有一種方法來掃描包含此宏的模板目錄並稍微更改宏代碼?vba - 掃描文件的宏和替換宏文本?
這可能嗎?
我被提出一個謎題。我工作的地方有大量的Word模板,它們都包含一個包含一些錯誤的autonew事件句柄。這個錯誤在所有模板中。我想知道是否可能有一種方法來掃描包含此宏的模板目錄並稍微更改宏代碼?vba - 掃描文件的宏和替換宏文本?
這可能嗎?
是的,你可以做到這一點。您可以使用任何文檔訪問VBA項目:
Application.VBE.ActiveVBProject.VBComponents
您的項目必須具有對「Microsoft Visual Basic for Applications Extensibility」的引用。
運行代碼,您必須啓用在Word選項 「到Visual Basic項目信託訪問」,使用
工具 - >宏觀>安全(可信 商選項卡)
VBComponents
集合包含項目包含的所有標準模塊,類模塊,表單和「文檔」模塊。如果你谷歌它,你會發現很多關於如何訪問/修改它們的幫助。
編輯:好的,一些更多的細節。此方法將搜索文檔的所有VbComponents
,查找具有指定名稱的方法,並在找到的第一個文檔內執行搜索/替換。
Public Sub ReplaceInProject(ByVal oDocument As Document, ByVal strMethodName As String, ByVal strFindText As String, ByVal strReplaceWithText As String)
' For each module (of any type - could use oVbComponent.Type to restrict
' this to certain types of module)
Dim oVbComponent As VBComponent
For Each oVbComponent In oDocument.VBProject.VBComponents
Dim oCodeModule As CodeModule
Set oCodeModule = oVbComponent.CodeModule
' See if we can find the method in this module
Dim ixStartLine As Long
ixStartLine = FindMethodStartLine(oCodeModule, strMethodName)
If ixStartLine > 0 Then
' Get all the text of the method
Dim numLines As Long
numLines = oCodeModule.ProcCountLines(strMethodName, vbext_pk_Proc)
Dim strLines As String
strLines = oCodeModule.Lines(ixStartLine, numLines)
' Do the find/replace
strLines = Replace(strLines, strFindText, strReplaceWithText)
' Replace the method text.
oCodeModule.DeleteLines ixStartLine, numLines
oCodeModule.InsertLines ixStartLine, strLines
End If
Next oVbComponent
End Sub
Private Function FindMethodStartLine(ByVal oCodeModule As CodeModule, ByVal strMethodName As String) As Long
FindMethodStartLine = 0
' ProcStartLine will raise an error if the method is not found;
' we'll just ignore the error and return -1
On Error Resume Next
FindMethodStartLine = oCodeModule.ProcStartLine(strMethodName, vbext_pk_Proc)
End Function
需要注意的是,因爲我使用vbext_pk_Proc
這隻會與Sub
和Function
方法,而不是財產Get/Set/Let
工作。這是一個PITA,你需要明確這一點。坦率地說,CodeModule
組件的整個API似乎幾乎設計得令人沮喪。例如,儘管VbComponent
對象具有Find
方法(您認爲這是一種查找要查找的文本的便捷方式),但實際上它返回True
或False
(!)。有用,我不認爲!
當他們這樣做時,這個API的設計者肯定有一個非常糟糕的宿醉。
謝謝:)所以我已經添加到我的項目並導入Microsoft.Vbe.Interop,但你知道我如何可以從Word文檔加載宏到我的Visual Studio項目中的文本框?然後編輯文本然後再保存回去? 或者最好是用宏生成一個Word文件,然後將該文件中的宏複製到下一個宏? – 2009-11-17 07:38:16
Thanx的更新!很棒! :) – 2009-11-19 09:02:42