![Googleスプレッドシートのすべてのセルの全角英数字を半角に置換する方法](https://iwb.jp/wp-content/uploads/2024/06/google-spreadsheet-replace-all-full-width-alphanumeric-characters-to-half-width.png)
すべての全角英数字を半角に置換する方法
Googleスプレッドシートを使用していると、セル内のテキストの全角英数字をすべて半角に置換して文字表記を統一したいことがあります。
例えば下図のように全角英数字と半角英数字が混合されていると、文章の見栄えが悪いので、すべて半角英数字に統一したほうが良いです。
全角英数字と半角英数字の混合だと、例えば「docomo」のようになっている場合、「docomo」で検索しても検出されないという問題も発生します。
![Googleスプレッドシートのすべてのセルの全角英数字を半角に置換する方法](https://iwb.jp/wp-content/uploads/2024/06/google-spreadsheet-replace-all-full-width-alphanumeric-characters-to-half-width.png)
Google Apps Scriptで全角英数字を置換する
Googleスプレッドシートは編集メニューから「検索と置換」を開けますが、「検索と置換」ではすべての全角英数字を一括で半角英数字に置換できません。
そのため、すべての全角英数字を一括で半角英数字に置換したい場合はApps Scriptを使用します。
Apps Scriptを使用するには拡張機能から「Apps Script」を選択します。
![拡張機能メニューのGoogle Apps Script](https://iwb.jp/wp-content/uploads/2024/06/google-docs-replace-all-full-width-alphanumeric-characters-to-half-width-apps-script.png)
選択後にApps Scriptエディタが表示されるので、以下のすべての全角英数字を半角に置換するApps Scriptのコードをコード.gs内に貼り付けて保存します。
function convertFullWidthToHalfWidth() {
const sheets = SpreadsheetApp.getActiveSpreadsheet().getSheets()
sheets.forEach(sheet => {
const range = sheet.getDataRange()
const values = range.getValues()
const newValues = values.map(row => {
return row.map(cell => {
if (typeof cell === 'string') {
return zen2Han(cell)
}
})
})
range.setValues(newValues)
})
}
function zen2Han(str) {
return str.replace(/[A-Za-z0-9]/g, function(s) {
return String.fromCharCode(s.charCodeAt(0) - 0xFEE0)
})
}
あとはconvertFullWidthToHalfWidth関数を選択して「実行」を押せば、Googleスプレッドシートのすべてのセルの「全角英数字」が「半角英数字」に置換されます。
![Apps Script Editor 実行ボタン](https://iwb.jp/wp-content/uploads/2024/06/google-spreadsheet-replace-all-full-width-alphanumeric-characters-to-half-width-apps-script.png)
↓このようにすべての全角英数字が半角に置換される。
![Apps Scriptで置換後のシート](https://iwb.jp/wp-content/uploads/2024/06/google-spreadsheet-replace-all-full-width-alphanumeric-characters-to-half-width-fix.png)
※ 初回実行時は「承認が必要です」のダイアログが表示されるので、承認してください。
すべてのシートを置換の対象にしているため、getSheets()を使用していますが、アクティブのシートのみを置換の対象にしたい場合は、getActiveSheet()を使用した以下のコードを使用してください。
function convertFullWidthToHalfWidth() {
const sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet()
const range = sheet.getDataRange()
const values = range.getValues()
const newValues = values.map(row => {
return row.map(cell => {
if (typeof cell === 'string') {
return zen2Han(cell)
}
})
})
range.setValues(newValues)
}
function zen2Han(str) {
return str.replace(/[A-Za-z0-9]/g, function(s) {
return String.fromCharCode(s.charCodeAt(0) - 0xFEE0)
})
}
手作業だと時間と労力がかかる
Googleスプレッドシート内の全角英数字を目視ですべて確認して、手作業で修正するとかなりの時間と労力がかかりますし、目視だと全角英数字の見落としも発生します。
Apps Scriptなら1回実行するだけですべての全角英数字を半角英数字に置換できますので、特に理由がなければApps Scriptで置換したほうが良いです。