2014年10月18日土曜日

仕事で覚えたEXCEL+VBA〜金額がプラスなら青字に、マイナスなら赤字に設定する

 EXCELで「プラス金額なら青字で、マイナス金額なら赤字で」わかりやく、色を付けたいことがある。
 そこで、EXCELで「選択」しているセル(複数かつ、点在していてもOK)について、
+5百万であれば、青字で+5百万円、−5百万円ならば、赤字で5百万円表示するVBAマクロは、以下のような感じ。
excergirl

  1. Sub minusakaandplusaoHK()
  2. Dim strPat As String
  3. Dim strTest As String
  4. '  -digits red
  5. For Each r In Selection
  6.   strTest =r.Value
  7.   Set RE =CreateObject("VBScript:RegExp")
  8.   Set Matches = RE.Execute (strTest)
  9.   strPat = "(¥-|−)([0-9]|[0−9])+(.|.)? ([0-9]|[0−9]) *百万円"   --- pattern for search
  10.   With RE
  11.     .Pattern = StrPat
  12.     .IgnoreCase =False
  13.     .Global = True
  14.   End With
  15.   Set Matches = RE.Exceutes(strTest)
  16.   If Matches.Count <> 0 then
  17.     For Each Match In Matches
  18.       r.Characters(Start:=Match.FirstIndex + 1,Length:=Match.Length).Font.ColorINdex = 3
  19.   Next
  20.   Endif
  21.  Next r
  22. '+digits blue
  23. For Each r In Selection
  24.   strTest =r.Value
  25.   Set RE =CreateObject("VBScript:RegExp")
  26.   Set Matches = RE.Execute (strTest)
  27.   strPat = "(¥+|+)[0-9]|[0−9])+(.|.)? ([0-9]|[0−9]) *百万円"   --- pattern for search
  28.   With RE
  29.     .Pattern = StrPat
  30.     .IgnoreCase =False
  31.     .Global = True
  32.   End With
  33.   Set Matches = RE.Exceutes(strTest)
  34.   If Matches.Count <> 0 then
  35.     For Each Match In Matches
  36.       r.Characters(Start:=Match.FirstIndex + 1,Length:=Match.Length).Font.ColorINdex = 5
  37.   Next
  38.   Endif
  39.  Next r
  40. End Sub
ポイントとしては、「選択」しているセルを取り出すFor Each r In Selectionと「+n百万円」を正規表現RegExpで見つけているところ。

ちょっと一息のコーナー。
 トマス ・H・クックの「鹿の死んだ夜」(染田屋茂 訳、文春文庫)は、月曜日に「自宅の窓ごしに眺めると、リアダンには街が、でたらめな音と方向性のない動きの巨大なパッチワークに見えた。」という描写で静かに始まる。
 もう、随分前にこの本と出会い、思い浮かべるたびにその哀しい余韻が印象に残っている。原書のタイトルは、ブラッド・イノセント(blood innocent)。何年も絶版になった原書を探していたところ、電子書籍の時代となり、kindle本を購入することができた。
 原書では、MONDAY Watching it from his window, Reardon saw the city only as an immense patchwork of random sound and direction-less movement. で始まる。
 immenseは、巨大ななんだー。kindle本は単語の意味がでるので、便利ですね。
 タイトルが「ブラッド・イノセント」ではなく、「鹿の死んだ夜」になっていることのも「いいね」ですが、原書を読み返すたびに、染田屋訳の凄さ、絶妙さを感じています。トマス・クックもこれが処女作というのも凄い。

0 件のコメント:

コメントを投稿