1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Office VBA RGBをColor番号へ変換する ヘキサクロス方式関数

Last updated at Posted at 2023-03-07

遅いです

今回は見た目でわかりやすい関数をという事になっています。
早くしたいならByteをIntegerにしたほうがいいですが、エラーを事前にはねるようにByte型を使っています。
したがってマイナス、255より大きい整数はエラーで処理が止まります。
また、VBAに実際にコードを貼ってみるとレイアウトが崩れますが仕様です。

原理

十進数を16進数にするHexの返り値はString型

一桁の場合、F-> 0Fとすることがポイントです。
この方法はRight関数を使うことで解決しました。

Color番号は16進数では青緑赤の順で並んでいる

ということは

赤   緑    青
       X
青   緑     赤

とすればいいということになります。16進(Hex)にしてクロス(RGB -> BGR)するのでヘキサクロス関数です。

16進数を10進数に変換するのはVal("&H")

"&H"&Hとして良い場合もありますが、今回は連結させるので使います。

コード

入るときに縦にRGBと並んでいるのが返るときには、縦にBGRのと赤(R)と青(B)がひっくり返っています。
また、難しい計算は必要ありません。単純に並べ替えるだけで結果を得ることができるのです。
遅いと言っても167百万回計算するような状況ですから、1回計算する程度では差はありません。
そうであれば可読性の高い、原理のわかりやすいコードを使うほうがいいでしょう。

' **** Detail About RGBtoColornumberByHexCrossL ********
' For Microsoft Office VBA
' Hex Cross Method Function
' VBA Hex Function Return String
' Usage    RGBtoColornumberByHexCrossL(255,0,12)
' Caution R and G and B is Byte Data Type,  Unsigned 0 to 255
' By Eacn R G B, 2 Digit Hex - > Cross!! 
'                             - B G R ->
'                               Combine!!
'                             -> Val(&H B G R) -> Hex To Decimal(Long)
' *****************************************************
Function RGBtoColornumberByHexCrossL(R As Byte, _
                                     G As Byte, _
                                     B As Byte) As Long
RGBtoColornumberByHexCrossL = _
         Val("&H" & Right("00" & Hex(B), 2) & _
                    Right("00" & Hex(G), 2) & _
                    Right("00" & Hex(R), 2))
End Function

Advance

もちろん16進数(文字列)のまま返してもいいわけです

Function RGBtoColornumberByHexCrossH(R As Byte, _
                                     G As Byte, _
                                     B As Byte) As String
RGBtoColornumberByHexCrossH = _
             "&H" & Right("00" & Hex(B), 2) & _
                    Right("00" & Hex(G), 2) & _
                    Right("00" & Hex(R), 2)
End Function

Adverse

逆に6桁の16進数をR、G、Bの10進数の配列(Integer)で返すのがこちら

Function ColorNumberToRGBbyHexCross(Hex6String As String)
Dim ar(0 To 2) As Integer
Dim sbuf As String * 6
  sbuf = Replace(Hex6String, "&h", "", 1, -1, vbTextCompare)
  ar(0) = Val("&h" & Mid(sbuf, 5, 2)) ' 56 Red
  ar(1) = Val("&h" & Mid(sbuf, 3, 2)) ' 34 Green
  ar(2) = Val("&h" & Mid(sbuf, 1, 2)) ' 12 Blue
  ColorNumberToRGBbyHexCross = ar
End Function

関数なのに計算式があまりない

256とかMODとか一切出てきていません。16進数に変換するだけでこんなに簡単になるのです。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?