mixiユーザー(id:23976709)

2017年11月12日23:03

16070 view

[Excel VBA] 外部テキストの文字列を一斉置換する関数。(UTF-8 アンド 通常版対応版)

1. 文字コード UTF-8 の場合
Call ReplaceUTF(一斉置換したいファイルのフルパス, 検索文字列, 置換文字列)
 
2. 文字コード UTF-8 以外の場合
Call ReplaceTXT(一斉置換したいファイルのフルパス, 検索文字列, 置換文字列)
 
[具体例]
フォルダ「C:\hinden\events.files\」内にある
ファイル「sheet001.htm」 (charset=UTF-8) の中に
「_parent」という文字列があったらすべて「_blank」という文字列に置き換えまくりたい。
 ↓ 
Call ReplaceUTF("C:\hinden\events.files\sheet001.htm", "_parent", "_blank")



[関数 : ReplaceUTF8]

'テキストを文字列置換 (文字コードがUTF-8の場合)
Public Function ReplaceUTF8(FileName As String, TargetText As String, Optional NewText As String = "")
Dim buf_strTxt As String '読み込みバッファ
'全文読み込み
With CreateObject("ADODB.Stream")
.Charset = "UTF-8"
.Open
.LoadFromFile FileName
buf_strTxt = .ReadText
.Close
End With

'置換処理
buf_strTxt = Replace(buf_strTxt, TargetText, NewText, , , vbTextCompare)

'全文書き込み
With CreateObject("ADODB.Stream")
.Charset = "UTF-8"
.Type = 2
.Open
.WriteText buf_strTxt
.SaveToFile (FileName), 2
.Close
End With
End Function



[関数 : ReplaceTXT]

'テキストを文字列置換 (通常版)
Public Function ReplaceTXT(FileName As String, TargetText As String, Optional NewText As String = "")
Dim fso As FileSystemObject 'ファイルシステムオブジェクト
Dim TXT As TextStream 'テキストストリームオブジェクト
Dim buf_strTxt As String '読み込みバッファ

On Error GoTo Func_Err:
'オブジェクト作成
Set fso = CreateObject("Scripting.FileSystemObject")
Set TXT = fso.OpenTextFile(FileName, ForReading)

'全文読み込み
buf_strTxt = TXT.ReadAll
TXT.Close

'元ファイルをリネームして、テンポラリファイル作成
Name FileName As FileName & "_"

'置換処理
buf_strTxt = Replace(buf_strTxt, TargetText, NewText, , , vbTextCompare)

'書込み用テキストファイル作成
Set TXT = fso.CreateTextFile(FileName, True)
'書込み
TXT.Write buf_strTxt
TXT.Close

'テンポラリファイルを削除
fso.DeleteFile FileName & "_"
'終了処理
Func_Exit:
Set TXT = Nothing
Set fso = Nothing
Exit Function
Func_Err:
MsgBox "Error Number : " & Err.Number & vbCrLf & Err.Description
GoTo Func_Exit:
End Function



このExcelに現物アリ。
 ↓ 
http://www2u.biglobe.ne.jp/~hinden/etc/excel/etc.xls



[関連する過去日記]

[「Ma_ho_Ma_ho_Family」のサイト。全ファイルの文字コードを一斉に「UTF-8」に改修]
http://hinden.at.webry.info/201711/article_6.html

上記 記事 に載せてある手順にて大体よろしかったんですけど、Excel VBA で自動作成しているページに、不具合 (文字化け) が発生しました (文字列の Replace 時に、アカンかったわけです)。それに対処したのが、今回の関数です。

これでもう、大丈夫。
 ↓ 
http://www2u.biglobe.ne.jp/~hinden/live

改修後の「まほまほファミリー」のホームページ。
 ↓ 
http://www2u.biglobe.ne.jp/~hinden/
フォト


[その他の、関連する過去日記]

[「Ma_ho_Ma_ho_Family」のサイト、一斉にページ更新しました。(VBAを自作して)]
http://hinden.at.webry.info/201710/article_20.html

[[Excel VBA] 表記ゆれを統一。英数字・記号はすべて半角に、カタカナは全角に置換。]
http://hinden.at.webry.info/201710/article_9.html





Excel VBAスパテク368 2007/2003/2002対応
翔泳社
福光 洋子
https://www.amazon.co.jp/Excel-VBA%E3%82%B9%E3%83%91%E3%83%86%E3%82%AF368-2007-2003-2002%E5%AF%BE%E5%BF%9C/dp/4798117455?SubscriptionId=AKIAJZPZKAA66PNS4ODQ&tag=hindenmahomah-22&linkCode=xm2&camp=2025&creative=165953&creativeASIN=4798117455





http://hinden.at.webry.info/201711/article_13.html
1 0

コメント

mixiユーザー

ログインしてコメントを確認・投稿する