Created
October 31, 2025 02:05
-
-
Save YujiFukami/1781b1cb4649f6c80bd3a36d7d37831b to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Public Sub ConvertSelection_AlphaNumToHalfWidth() | |
| '【概要】 | |
| ' 選択範囲のセルに含まれる文字列から、 | |
| '「全角英字・全角数字(および同範囲の基本記号)」のみを半角へ変換する。 | |
| ' カタカナ・全角スペース・漢字は変換対象外。 | |
| ' | |
| '【処理例】 | |
| ' ABC123 → ABC123 | |
| ' Hello! → Hello! | |
| ' テスト123 → テスト123 | |
| ' カタカナABC → カタカナABC | |
| ' 全角スペース → 全角スペース(変換しない) | |
| Dim SelectedCell As Range ' 選択セル範囲(処理対象の外枠) | |
| Dim Cell As Range ' ループ用:各セル | |
| Dim Text As String ' 元のセル文字列(1セル分) | |
| Dim I As Long ' 文字走査用インデックス(1-based) | |
| Dim TmpStr As String ' 現在走査中の1文字 | |
| Dim Code As Long ' 1文字のUnicodeコードポイント(AscWの戻り) | |
| Dim Result As String ' 変換後の文字列(1セル分の組み立て結果) | |
| On Error GoTo ErrorHandler | |
| Set SelectedCell = Selection | |
| For Each Cell In SelectedCell | |
| If VarType(Cell.Value) = vbString Then | |
| Text = Cell.Value | |
| Result = "" | |
| For I = 1 To Len(Text) | |
| TmpStr = Mid$(Text, I, 1) | |
| Code = AscW(TmpStr) | |
| ' 【全角英数字(!~~)の範囲】を半角に変換 | |
| If Code >= &HFF01 And Code <= &HFF5E Then | |
| ' 全角英数字を半角に変換 | |
| Result = Result & ChrW(Code - &HFEE0) | |
| Else | |
| ' それ以外(カタカナ・漢字・記号など)はそのまま | |
| Result = Result & TmpStr | |
| End If | |
| Next I | |
| ' 結果を反映 | |
| If Text <> Result Then Cell.Value = Result | |
| End If | |
| Next Cell | |
| MsgBox "全角英数字を半角に変換しました(カタカナは除外)。", vbInformation | |
| Exit Sub | |
| ErrorHandler: | |
| MsgBox "エラー: " & Err.Description, vbExclamation | |
| End Sub |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment