Hàm chuyển đổi text Unicode tiếng Việt VBA dùng trên Excel

0
62

Hiển thị Unicode (tiếng Việt) trên VBA hiện nay vẫn đang là một vấn đề. Để giải quyết vấn đề này chúng ta có thể sử dụng hàm UnicodeVba

Đầu tiên tạo mới một file Excel và lưu lại với phần mở rộng .xlsm (Excel Macro-Enabled Workbook)

Lựa chọn “Developer” → “Visual Basic

Lựa chọn “Insert” → “Module

Copy đoạn Code sau

'Attribute VB_Name = "modCommon"
Option Explicit
Function UnicodeVba(txtUnicode As String) As String
    Dim n As Integer
    Dim uni1 As String
    Dim uni2 As String
    If txtUnicode = "" Then
        UnicodeVba = """"""
    Else
        txtUnicode = txtUnicode & " "
        If AscW(Left(txtUnicode, 1)) < 256 Then UnicodeVba = """"
        For n = 1 To Len(txtUnicode) - 1
            uni1 = Mid(txtUnicode, n, 1)
            uni2 = AscW(Mid(txtUnicode, n + 1, 1))
            
            If AscW(uni1) > 255 And uni2 > 255 Then
                UnicodeVba = UnicodeVba & "ChrW(" & AscW(uni1) & ") & "
            ElseIf AscW(uni1) > 255 And uni2 < 256 Then
                UnicodeVba = UnicodeVba & "ChrW(" & AscW(uni1) & ") & """
            ElseIf AscW(uni1) < 256 And uni2 > 255 Then
                UnicodeVba = UnicodeVba & uni1 & """ & "
            Else
                UnicodeVba = UnicodeVba & uni1
            End If
        Next
      
        If Right(UnicodeVba, 4) = " & """ Then
            UnicodeVba = Mid(UnicodeVba, 1, Len(UnicodeVba) - 4)
        Else
            UnicodeVba = UnicodeVba & """"
        End If
    End If
End Function

Dán vào Module Code vừa tạo

Ấn “Alt + Q” để quay trở lại Excel. Hàm UnicodeVba giờ đã sẵn sàng sử dụng

Chúng ta chỉ việc Copy kết quả của hàm UnicodeVba dán vào đoạn muốn hiển thị tiếng Việt trong VBA

BÌNH LUẬN

Vui lòng nhập bình luận của bạn
Vui lòng nhập tên của bạn ở đây