|
本帖最后由 perfect131 于 2022-11-21 13:10 编辑
TXT文件 标准编码有 ANSI,UTF-16LE,UTF-16BE,NO BOM UTF-8,UTF-8
vba 代码
- ''FilePath 是TXT文件绝对路径,D:\excelhome\1.txt
- Function 编码(FilePath As String)
- Dim Data
- With CreateObject("ADODB.Stream")
- .Open
- .Type = 1
- .LoadFromFile FilePath
- Data = .Read
- .Close
- End With
- If IsNull(Data) Then 编码 = "NO BOM UTF-8": Exit Function
- If UBound(Data) < 1 Then 编码 = "NO BOM UTF-8": Exit Function
- If UBound(Data) >= 1 Then
- If UBound(Data) > 1 Then
- If Hex(Data(0)) = "EF" And Hex(Data(1)) = "BB" And Hex(Data(2)) = "BF" Then
- 编码 = "UTF-8": Exit Function
- End If
- End If
- Select Case Hex(Data(0)) & Hex(Data(1))
- Case "FEFF"
- 编码 = "UTF-16 big endian": Exit Function
- Case "FFFE"
- 编码 = "UTF-16 little endian": Exit Function
- Case Else
- CanBeUTF8 = True
- For i = 1 To LenB(Data)
- FirstByte = AscB(MidB(Data, i, 1))
- If &H0 <= FirstByte And FirstByte <= &H7F Then
- FollowingBytesCount = 0
- ElseIf &HC2 <= FirstByte And FirstByte <= &HDF Then
- FollowingBytesCount = 1
- ElseIf &HE0 <= FirstByte And FirstByte <= &HEF Then
- FollowingBytesCount = 2
- ElseIf &HF0 <= FirstByte And FirstByte <= &HF4 Then
- FollowingBytesCount = 3
- Else
- CanBeUTF8 = False: Exit For
- End If
- For j = 1 To FollowingBytesCount
- i = i + 1
- If i > LenB(Data) Then
- CanBeUTF8 = False: Exit For
- End If
- FollowingByte = AscB(MidB(Data, i, 1))
- If (&H80 <= FollowingByte And FollowingByte <= &HBF) = False Then
- CanBeUTF8 = False: Exit For: i = LenB(Data) + 1
- End If
- Next
- Next
- 编码 = IIf(CanBeUTF8, "NO BOM UTF-8", "ANSI"): Exit Function
- End Select
- End If
- End Function
复制代码 实际案例 6楼:https://club.excelhome.net/threa ... tml?_dsign=29dceccc
|
|