ExcelVBA覚書 正規表現

私が苦手なものの1つ「正規表現」
いつまでも逃げられないので、がんばってみた。

まずは整数

'整数(上限が5桁 -99999~99999はOK)
Dim rng As Range           '対象セル
Dim res As Boolean         '結果

Set rng = ActiveCell       '選択しているセルをチェックする
Set reg = CreateObject("VBScript.RegExp")
With reg
     .IgnoreCase = True             '大文字小文字は関係ない
     .Global = True                 '全体をチェック
     .Pattern = "^[-]?[0-9]{1,5}$"
     If .Test(rng.Value) Then
          res = True
          Exit Function
     End If
End With

次は実数
こいつがややこしくて、整数のときと実数のときとで分けてやらないといけない
.Pattern = “^[-]?[0-9]{1,3}[.]?[0-9]{0,2}$”
だけにすると整数4桁、5桁の数値もOKになってしまった。

'実数(上限が5桁 -999.99~999.99はOK)
Dim rng As Range           '対象セル
Dim res As Boolean         '結果

Set rng = ActiveCell      
Set reg = CreateObject("VBScript.RegExp")
With reg
     .IgnoreCase = True   
     .Global = True       
     '整数の場合のチェック
     .Pattern = "^[-]?[0-9]{1,3}$"
     If .Test(rng.Value) Then
          res = True
          Exit Function
     End If
     '実数の場合のチェック
     .Pattern = "^[-]?[0-9]{1,3}[.]{1,1}[0-9]{0,2}$"
     If .Test(rng.Value) Then
          res= True
          Exit Function
     End If    
End With

そして、英数字のみ

'英数字のみ(上限が5桁で、半角のみ、大文字小文字OK)
Dim rng As Range           '対象セル
Dim res As Boolean         '結果

Set rng = ActiveCell      
Set reg = CreateObject("VBScript.RegExp")
With reg
     .IgnoreCase = True   
     .Global = True       
     .Pattern = "^[a-z0-9]{0,5}$"
     If .Test(rng.Value) Then
          res = True
          Exit Function
     End If     
End With
Tags:,

Add a Comment

メールアドレスが公開されることはありません。 が付いている欄は必須項目です

このサイトはスパムを低減するために Akismet を使っています。コメントデータの処理方法の詳細はこちらをご覧ください