見出し画像

携帯電話番号の書式が違うセルを青色にするよ

この説明は、ChatGPTで作成しています。

このVBAコードは、選択されたセルの中から 「正しい形式の携帯電話番号」 ではないものを見つけて、背景を青色に変更するためのものです。ここで使われている「正しい形式」とは、「123-4567-8901」 のように、ハイフンで区切られた日本の携帯電話番号の形式を指しています。


仕組みの説明

  1. 画面更新の停止
    `Application.ScreenUpdating = False`
    この部分で、画面の更新を一時的に停止しています。これにより、処理が早くなり、コードが実行されている間に画面がちらつくのを防ぎます。

  2. 正規表現のオブジェクト作成
    `Set reg = CreateObject("VBScript.RegExp")`
    ここでは、VBScriptの 正規表現 を使うためのオブジェクトを作成しています。正規表現とは、特定の文字列のパターンをチェックするための技術です。

  3. 選択範囲のチェック
    `For Each myRng In Selection`
    選択されたセル範囲を1つずつチェックしていきます。

  4. 画面更新の再開
    `Application.ScreenUpdating = True`
    最後に、画面更新を再開します。


このコードは、例えばExcelでたくさんの携帯電話番号が入力されたリストがある場合に、 「書式が間違っている番号をすぐに見つけたい」 というときに便利です。

Sub 携帯電話番号の書式が違うセルを青色にするよ()
    Application.ScreenUpdating = False
            
    Dim reg
    Set reg = CreateObject("VBScript.RegExp")   'オブジェクト作成
    Dim myRng As Range
    Dim txt As String
    With reg
        .Pattern = "^\d{3}-\d{4}-\d{4}$"
        .IgnoreCase = True
        .Global = True
    End With
    On Error Resume Next
    For Each myRng In Selection
            txt = myRng.Value
            If Not reg.Test(txt) Then
                myRng.Interior.ColorIndex = 5
            End If
    Next myRng
    Application.ScreenUpdating = True
End Sub

キーワード

#excel #できること #vba #正規表現 #書式チェック #セル色変更 #自動化 #携帯電話番号 #テキスト処理 #プログラミング初心者 #Excel自動化 #色分け #電話番号確認 #データ管理 #選択範囲 #ハイフン形式 #セル操作 #画面更新制御 #コード解説 #条件付き書式


"Change the Background Color of Cells with Incorrect Phone Number Format" (English Translation)

This explanation is created using ChatGPT.

This VBA code is designed to find cells that do not contain a "correctly formatted phone number" from a selected range and change their background to blue. The "correct format" here refers to a Japanese mobile phone number like "123-4567-8901" with hyphens separating the digits.


How It Works

  1. Stopping Screen Updates
    `Application.ScreenUpdating = False`
    This temporarily stops screen updates, making the process faster and preventing flickering while the code runs.

  2. Creating a Regular Expression Object
    `Set reg = CreateObject("VBScript.RegExp")`
    This creates an object for using regular expressions in VBScript, which is a technique for checking specific patterns in text.

  3. Checking the Selected Range
    `For Each myRng In Selection`
    It loops through each selected cell in the range.

  4. Restarting Screen Updates
    `Application.ScreenUpdating = True`
    Finally, screen updates are resumed.


This code is particularly useful if you have a list of phone numbers in Excel and want to "quickly spot numbers with incorrect formatting".


Keywords

#excel #whatyoucando #vba #regex #formatcheck #changecellcolor #automation #phonenumber #textprocessing #beginnerprogramming #Excelautomation #colorcoding #phoneverification #datamanagement #selectedrange #hyphenformat #celloperations #screenupdatingcontrol #codeexplanation #conditionalformatting

この記事が気に入ったらサポートをしてみませんか?