其實,這個問題很簡單 ,可偏偏很多人不知道,於是寫了這個
先用2進制方式打開文件,讀出數據到byte數組中,然後用copymemory去掉文件頭(頭兩個字符分別是FF FE
(16進制))得到一個新的byte數組,最後利用strconv函數即可,下面給出代碼:
Option Explicit
Private Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (Destination As Any, source
As Any, ByVal Length As Long)
Private Function ReadUniFile(ByVal sFile As String) As String
'沒加錯誤處理,大家自己加吧
Dim a As Long
a = FileLen(sFile)
ReDim buff(a - 1) As Byte
ReDim buff1(a - 3) As Byte
Open sFile For Binary As #1
Get #1, , buff
Close #1
CopyMemory buff1(0), buff(2), a - 2
Dim s As String
s = StrConv(buff1, vbNarrow)
ReadUniFile = s
End Function
自己的宏
Sub 讀取txt文件()
With ActiveSheet.QueryTables.Add(Connection:="TEXT;c:\123.txt", Destination:=Range("A1"))
.Name = "123"
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.TextFilePromptOnRefresh = False
.TextFilePlatform = 936
.TextFileStartRow = 1
.TextFileParseType = xlDelimited
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = False
.TextFileTabDelimiter = True
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = False
.TextFileSpaceDelimiter = False
.TextFileColumnDataTypes = Array(1, 1, 1, 1, 1)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With
End Sub