♪僕はこんなコードであんなコードで 時を乗り越えてきた~
相変わらずの素人くさいコードですが動きゃーいいのです。
ワードのマクロはクセがあるよねぇ~。
エクセルからワード開いて検索、削除とかするとき。
Private Declare PtrSafe Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As LongPtr)
Function おやおや(fName As String) As Boolean
Dim fPath As String: fPath = ThisWorkbook.Path
Dim wApp: Set wApp = CreateObject("Word.Application")
wApp.Visible = True
’ワードのファイルを開くよ
Dim wFile As Word.Document: Set wFile = wApp.Documents.Open(fPath & "\" & fName)
Sleep 40
’駄目だったら死ぬ
If wFile Is Nothing Then Exit Function
wFile.Activate
子処理1 fName
子処理2 wApp, fName
’別名で保存
wFile.SaveAs2 (fPath & "\" & Range("A1") & "_" & fName)
wFile.Close
wApp.Quit
End Function
Function 子処理1(fName As String) As Boolean
’WORDこれで行けるときもあるけどエラー出ることが多い。アプリケーションごと渡したほうが良さげ
With Word.Documents(fName).Parent.Selection
With .Find
.ClearFormatting
.Replacement.ClearFormatting
.Wrap = wdFindContinue
.Text = "hogehoge"
.MatchWholeWord = True
.Forward = True
.Execute
End With
.EndKey Unit:=wdStory, Extend:=wdExtend
.Delete
.InsertAfter vbNewLine & "もうhogehogeなんて言わないよ絶対"
wApp.Selection.HomeKey Unit:=wdStory
End With
End Function
Function 子処理2(wApp, fName As String) As Boolean
’WORDの型指定すると怒られる。なんで?
With wApp.Selection
With .Find
.ClearFormatting
.Replacement.ClearFormatting
.Wrap = wdFindContinue
.Text = "hogehoge"
.MatchWholeWord = True
.Forward = True
.Execute
End With
.EndKey Unit:=wdStory, Extend:=wdExtend
.Delete
.InsertAfter vbNewLine & "もうhogehogeなんて言わないよ絶対"
wApp.Selection.HomeKey Unit:=wdStory
End With
End Function
あと正規表現文章全部対象にする時
Dim reg As New RegExp
Dim cols As MatchCollection
reg.Pattern = "(○|●|6)ヶ月"
Set cols = reg.Execute(wApp.Documents(fName).Range.Text)
Dim col
Dim i As Integer
For Each col In cols
’SubMatchesの使い方がいまいち分かんねぇ。
For i = 0 To col.SubMatches.Count - 1
Next
Next