LeftBでは末尾の全角文字列1バイトが切られてしまう場合、末尾の全角文字列が文字化けする。
全角文字列の文字化けを考慮する場合は別途チェックが必要になる。
■文字化け回避用のLeftB拡張モジュールサンプル(末尾切り上げ/切り捨て、全半角混在も対応)
- ' 引数説明
- ' prm:対象文字列
- ' length:取得バイト数
- ' convert:True時Nullを""に変換/False時Nullをそのまま返す
- ' truncate:True時末尾切り捨て /False時末尾切り上げ
- Private Function ExLeftB(ByVal prm As Variant, _
- ByVal length As Integer, _
- Optional ByVal convert As Boolean = True, _
- Optional ByVal truncate As Boolean = True) As Variant
- Dim cnvStr As String
- ' Accessの場合
- cnvStr = StrConv(Nz(prm, ""), vbFromUnicode)
- ' Excelの場合
- ' cnvStr = StrConv(IIf(IsNull(prm), "", prm), vbFromUnicode)
- If LenB(cnvStr) <= length Then
- ExLeftB = IIf(convert, Nz(prm), prm)
- Exit Function
- End If
- Dim leftNormal As Variant
- Dim leftTrunc As Variant
- Dim leftRoundUp As Variant
- leftNormal = StrConv(LeftB(cnvStr, length), vbUnicode)
- leftTrunc = StrConv(LeftB(cnvStr, length - 1), vbUnicode)
- leftRoundUp = StrConv(LeftB(cnvStr, length + 1), vbUnicode)
- If Len(leftNormal) <> Len(leftRoundUp) Then
- ExLeftB = leftNormal
- Exit Function
- Else
- ExLeftB = IIf(truncate, leftTrunc, leftRoundUp)
- Exit Function
- End If
- End Function
■使用例
- Private Sub dammy()
- Debug.Print ("---------------------")
- Debug.Print ("Nullコンバートする")
- Debug.Print (ExLeftB(Null, 3))
- Debug.Print ("---------------------")
- Debug.Print ("Nullコンバートしない")
- Debug.Print (ExLeftB(Null, 3, False))
- Debug.Print ("---------------------")
- Debug.Print ("切り捨て出力")
- Debug.Print (ExLeftB("あああ", 5))
- Debug.Print ("---------------------")
- Debug.Print ("切り上げ出力")
- Debug.Print (ExLeftB("あああ", 5, truncate:=False))
- Debug.Print ("---------------------")
- End Sub
■実行結果

0 件のコメント:
コメントを投稿