0
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 5 years have passed since last update.

ExcelのLEFTB/MIDB/RIGHTBで半角スペースを殺すユーザ定義関数

Last updated at Posted at 2019-07-30

概要

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
0
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
0
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?