コード
文字列を置換するマクロ処理.xlsm
' -------------------------------------------------------------------------------------------
' 文字列を置換するマクロ処理
' -------------------------------------------------------------------------------------------
Sub GenerateReplacementData()
'-------------------------------------------------------------------------------------------
' 定義
'-------------------------------------------------------------------------------------------
Dim ws_Replacement As Worksheet
Dim ws_Base As Worksheet
' 行数
Dim rowIndex As Long
' While文内での調べる行数
Dim checkIndex As Long
'-------------------------------------------------------------------------------------------
' 初期化
'-------------------------------------------------------------------------------------------
Set ws_Replacement = ThisWorkbook.Sheets("置換する文字列")
Set ws_Base = ThisWorkbook.Sheets("元の文字列")
rowIndex = GetHeaderColumnCount(ws_Replacement)
checkIndex = 1
' 出力先を初期化する
ws_Base.Columns(2).ClearContents
ws_Base.Cells(1, 2).Value = "↓エクスポートされた文字列↓"
'-------------------------------------------------------------------------------------------
' 一行ずつ置換文字を確認し、生成した文字を出力する
'-------------------------------------------------------------------------------------------
Do While True
Dim textData As String
textData = ws_Base.Cells(2, 1).Value
checkIndex = checkIndex + 1
' 指定した行の最前列にデータがない場合終了
If ws_Replacement.Cells(checkIndex, 1).Value = "" Then
Exit Do
End If
' 1列ずつ置換処理
For i = 1 To rowIndex
Dim checkText As String
Dim newText As String
checkText = ws_Replacement.Cells(1, i).Value
newText = ws_Replacement.Cells(checkIndex, i).Value
textData = OnReplacement(textData, checkText, newText)
Next i
' 出力
ws_Base.Cells(checkIndex, 2).Value = textData
Loop
MsgBox "置換成功!", vbInformation
End Sub
'-------------------------------------------------------------------------------------------
'一行目の列数を返す
Function GetHeaderColumnCount(ws As Worksheet) As Long
lastCol = ws.Cells(1, ws.Columns.Count).End(xlToLeft).Column
countUsedCols = 0
Dim colIndex As Long
For colIndex = 1 To lastCol
If ws.Cells(1, colIndex).Value <> "" Then
countUsedCols = countUsedCols + 1
Else
Exit For
End If
Next colIndex
GetHeaderColumnCount = countUsedCols
End Function
'-------------------------------------------------------------------------------------------
' 置換処理をしてテキストを生成する
Function OnReplacement(originalText As String, targetText As String, newText As String) As String
OnReplacement = Replace(originalText, targetText, newText)
End Function
導入
1.マクロの開発画面を表示
Excel上部に開発タブがあるのでクリック
無い場合は、ファイル → オプション → リボンのユーザー設定 → 開発にチェックを入れてOKを押す
開発タブを押したら、1番左にあるVisualBasicをクリック。VisualBasicタブが開く
2.マクロのプログラムをコピペ
VisualBasicの上のタブから、挿入 → 標準モジュールをクリック
マクロのスクリプトをコピペする
3.マクロをショートカットキーで実行できるようにする
Excelの 表示 → マクロ → オプション で好きなショートカットに設定
4.シートを追加する
「置換する文字列」シートと「元の文字列」シートを作成する
「置換する文字列」シートは、1行目をウィンドウ枠の固定をする
使い方
1.「置換する文字列」シートで、置換要素を1行目、置換後の文字列を2行目以降に書く
2.「元の文字列」シートで、置換場所を含んだ文字列を A2 に設定
3.実行すると、置換された文字列が「置換する文字列」シートの B2 以降に出力
※「置換する文字列」シートに関して、A列を見て置換するかどうかを見ているので、必ず設定してください。