Adsense

2019年8月27日火曜日

【ACCESS/EXCEL/VBA】末尾全角文字化け回避用 拡張LeftBサンプル



LeftBでは末尾の全角文字列1バイトが切られてしまう場合、末尾の全角文字列が文字化けする。
全角文字列の文字化けを考慮する場合は別途チェックが必要になる。


■文字化け回避用のLeftB拡張モジュールサンプル(末尾切り上げ/切り捨て、全半角混在も対応)
  1. ' 引数説明
  2. ' prm:対象文字列
  3. ' length:取得バイト数
  4. ' convert:True時Nullを""に変換/False時Nullをそのまま返す
  5. ' truncate:True時末尾切り捨て /False時末尾切り上げ
  6. Private Function ExLeftB(ByVal prm As Variant, _
  7. ByVal length As Integer, _
  8. Optional ByVal convert As Boolean = True, _
  9. Optional ByVal truncate As Boolean = True) As Variant
  10. Dim cnvStr As String
  11. ' Accessの場合
  12. cnvStr = StrConv(Nz(prm, ""), vbFromUnicode)
  13. ' Excelの場合
  14. ' cnvStr = StrConv(IIf(IsNull(prm), "", prm), vbFromUnicode)
  15. If LenB(cnvStr) <= length Then
  16. ExLeftB = IIf(convert, Nz(prm), prm)
  17. Exit Function
  18. End If
  19. Dim leftNormal As Variant
  20. Dim leftTrunc As Variant
  21. Dim leftRoundUp As Variant
  22. leftNormal = StrConv(LeftB(cnvStr, length), vbUnicode)
  23. leftTrunc = StrConv(LeftB(cnvStr, length - 1), vbUnicode)
  24. leftRoundUp = StrConv(LeftB(cnvStr, length + 1), vbUnicode)
  25. If Len(leftNormal) <> Len(leftRoundUp) Then
  26. ExLeftB = leftNormal
  27. Exit Function
  28. Else
  29. ExLeftB = IIf(truncate, leftTrunc, leftRoundUp)
  30. Exit Function
  31. End If
  32. End Function
  33.  


■使用例
  1. Private Sub dammy()
  2. Debug.Print ("---------------------")
  3. Debug.Print ("Nullコンバートする")
  4. Debug.Print (ExLeftB(Null, 3))
  5. Debug.Print ("---------------------")
  6. Debug.Print ("Nullコンバートしない")
  7. Debug.Print (ExLeftB(Null, 3, False))
  8. Debug.Print ("---------------------")
  9. Debug.Print ("切り捨て出力")
  10. Debug.Print (ExLeftB("あああ", 5))
  11. Debug.Print ("---------------------")
  12. Debug.Print ("切り上げ出力")
  13. Debug.Print (ExLeftB("あああ", 5, truncate:=False))
  14. Debug.Print ("---------------------")
  15. End Sub

■実行結果

0 件のコメント:

コメントを投稿