2009-08-19 16:46:27楓冬彥
[SOFT]VBA Word 巨集 小修改 Office
今天有朋友問我
想要在 Word裡面 搜尋某段字串 找到就刪除某幾行
1.我先請他 錄製巨集(如果常用且刪除行數有固定的話)
Sub 巨集2()
Selection.Find.ClearFormatting
With Selection.Find
.Text = "XXXXXX"
.Replacement.Text = ""
.Forward = True
.Wrap = wdFindContinue
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchByte = True
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
End With
Selection.Find.Execute
Selection.MoveDown Unit:=wdLine, Count:=2
Selection.MoveUp Unit:=wdLine, Count:=19, Extend:=wdExtend
Selection.Delete Unit:=wdCharacter, Count:=1
End Sub
2.但是 跑到最後找不到時會刪除最後幾行;希望能自動從頭做到尾
所以 幫他加了 判斷+迴圈
Do While Selection.Find.Execute
Selection.MoveDown Unit:=wdLine, Count:=2
Selection.MoveUp Unit:=wdLine, Count:=19, Extend:=wdExtend
Selection.Delete Unit:=wdCharacter, Count:=1
Loop
3.醬就搞定了 如果想要將巨集傳給別人 不是直接將word檔給對方
最好另外將巨集程式碼也COPY給對方 否則WORD檔本身是不含巨集的(預設放在WORD系統用檔案裡面)
PS>如果每次執行巨集只想做一次的話 可用IF就好
IF Selection.Find.Execute Then
Selection.MoveDown Unit:=wdLine, Count:=2
Selection.MoveUp Unit:=wdLine, Count:=19, Extend:=wdExtend
Selection.Delete Unit:=wdCharacter, Count:=1
End IF