Environment
- OS: Windows 10 Pro (Version: 20H2)
- Software: Microsoft Excel VBA
Background
When processing values read from a barcode reader using VBA, I encountered a significant issue where the input was being interpreted as Full-Width (Zenkaku) characters. This caused data mismatch errors.
To solve this, I learned how to convert these Full-Width characters into Half-Width (Hankaku) characters.
Solution: Use the StrConv Function (vbNarrow)
In VBA, you can easily convert Full-Width characters to Half-Width using the StrConv function.
Code Example (Converting Barcode Input to Half-Width)
Sub ConvertBarcodeToHalfWidth()
Dim barcode_raw As String
Dim barcode As String
' Get input from the user (Type:=2 specifies Text)
barcode_raw = Application.InputBox(Prompt:="Please scan the barcode.", Title:="Barcode Form", Type:=2)
' Convert the raw input to Half-Width (vbNarrow)
barcode = StrConv(barcode_raw, vbNarrow)
' Output the result (for verification)
MsgBox "Converted Value: " & barcode
End Sub
Code Explanation
- Lines 2-3: Declare string variables
barcode_raw(for raw input) andbarcode(for the converted result). - Line 6: Display an
InputBoxfor barcode scanning and store the value inbarcode_raw.- Note: We use
Type:=2to specify Text input.
- Note: We use
- Line 9: Use the
StrConvfunction to convert the content ofbarcode_rawto Half-Width by specifying thevbNarrowconstant. The result is stored in thebarcodevariable.
This ensures that even if the barcode scanner inputs Full-Width characters, they are automatically normalized to Half-Width.
Lessons Learned from Failed Attempts
Before finding this solution, I attempted to solve the issue using xlIMEMode properties or the CStr() function. However, I faced the following problems:
- Object-related errors: Setting IME modes works for entering data into cells but does not convert data already received in a variable.
- Type conversion issues:
CStr()changes the data type to a string but does not change the character width (Full-Width remains Full-Width).
I realized that StrConv + vbNarrow is the simplest and most reliable method for this specific task.
Summary
To convert Full-Width characters to Half-Width in VBA, use the following syntax:
StrConv(TargetString, vbNarrow)
This is the easiest and most certain method. It is particularly effective in scenarios requiring strict data standardization, such as barcode processing or database registration.
