スナックelve 本店

バツイチ40代女の日記です

人生に不安を感じたらエクセルを開こう(ワードの話)

♪僕はこんなコードであんなコードで 時を乗り越えてきた~

相変わらずの素人くさいコードですが動きゃーいいのです。
ワードのマクロはクセがあるよねぇ~。

エクセルからワード開いて検索、削除とかするとき。

'sleep 64bitはこうらしい
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
	'最初に見つかったhogehogeから最後まで選択
	.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
	'最初に見つかったhogehogeから最後まで選択
	.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)ヶ月"
	'ここがよくわからなくてハマった。selectionとかじゃねーの。
	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
			'colに見つかった文字列(例●ヶ月)とか入ってるから
			'ここで検索とか置換とかすればいいのかなぁ
		Next
	Next