日: 2015年2月18日

ExcelVBA覚書 セルにコメントをつける

セルにコメント(ふきだし)をつけるやり方。

Dim rng As Range
Dim msg As String
Dim clear_flg As Boolean

'選択中のセルにコメントを追加していく
Set rng = ActiveCell
msg = "あいうえお"
clear_flg = False         'コメントを刷新するときはTrueに変える

On Error Resume Next
If Not rng.Comment Is Nothing Then
    If clear_flg Then
        rng.Comment.Text  msg        '刷新
    Else
        rng.Comment.Text rng.Comment.Text() & vbNewLine
                         & msg       '追記
    End If
    Exit Sub
End If

'新しいコメントを追加する
With rng.AddComment(msg)
    .Shape.TextFrame.Characters.Font.ColorIndex = 2 'フォントは白
    .Shape.TextFrame.Characters.Font.Size = 9
    .Shape.TextFrame.AutoSize = True
    .Shape.Fill.ForeColor.RGB = RGB(0, 0, 0)         '背景は黒
    .Visible = True
End With

clear_flg=Trueならば、コメントは置き換わるが、Falseならば改行して追記していく。
なので、コメントは自動サイズ設定(AutoSize=True)にしておく。

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