概要
ExcelのLEFTB()
/RIGHTB()
/MIDB()
関数は切り出した文字の先頭/末尾が2バイト文字の途中だった場合、その文字が半角スペースになってしまいます。
この時に半角スペースを入れないで切り出す関数をLEFTBS()
/RIGHTBS()
/MIDBS()
関数としてVBAで作成します。
ソース
基本方針は、VBAでMidB
関数を使って2バイト文字の途中を切り出した場合に戻り値が0
になることを利用して、切り出し位置と切り出しバイト数を調整します。
全角2バイト、半角1バイトとして切り出せるようにstrConv
でUNICODEからShiftJISに変換して判定する必要があることに注意。
LEFTBS(文字列[, バイト数])
LEFTBS
の場合は単純で、判定結果が0
だったら切り出しバイト数を-1
するだけです。
Public Function LEFTBS(strParamString As String, Optional lngParamByte As Long = 1) As String
Dim lngByte
lngByte = lngParamByte
If lngParamByte >= LenB(StrConv(strParamString, vbFromUnicode)) Then
LEFTBS = strParamString
Else
If MidB(StrConv(strParamString, vbFromUnicode), lngParamByte, 1) <> 0 Then
lngByte = lngByte - 1
End If
LEFTBS = StrConv(LeftB(StrConv(strParamString, vbFromUnicode), lngByte), vbUnicode)
End If
End Function
RIGHTBS(文字列[, バイト数])
RIGHTBS
の場合、MidB
で判定する最初の1バイトが全体のバイト数 - 切り出しバイト数
になります。
Public Function RIGHTBS(strParamString As String, Optional lngParamByte As Long = 1) As String
Dim lngByte As Long
lngByte = lngParamByte
If lngParamByte >= LenB(StrConv(strParamString, vbFromUnicode)) Then
RIGHTBS = strParamString
Else
If MidB(StrConv(strParamString, vbFromUnicode), LenB(StrConv(strParamString, vbFromUnicode)) - lngParamByte, 1) <> 0 Then
lngByte = lngByte - 1
End If
RIGHTBS = StrConv(RightB(StrConv(strParamString, vbFromUnicode), lngByte), vbUnicode)
End If
End Function
MIDBS(文字列, 開始位置, バイト数)
MIDBS
の場合、先頭1文字の判定結果が0
だった場合開始位置を+1
し、その分切り出しバイト数を-1
します。
続いて末尾1文字を判定して、0
だった場合は切り出しバイト数をさらに-1
する、という流れです。
Public Function MIDBS(strParamString As String, lngParamStart As Long, lngParamByte As Long) As String
Dim lngStart As Long
lngStart = lngParamStart
Dim lngByte As Long
lngByte = lngParamByte
If MidB(StrConv(strParamString, vbFromUnicode), lngParamStart, 1) = 0 Then
lngStart = lngStart + 1
lngByte = lngByte - 1
End If
If MidB(StrConv(strParamString, vbFromUnicode), lngParamStart + lngParamByte, 1) = 0 Then
lngByte = lngByte - 1
End If
MIDBS = StrConv(MidB(StrConv(strParamString, vbFromUnicode), lngStart, lngByte), vbUnicode)
End Function