vba中读取utf-8格式的csv文件保证不乱码
EXCEL中的导入data的功能。(data-> import external data)
Sub Macro1()
'' Macro1 Macro
' test for sunhaifeng
' sunhf@cn.ibm.com
'
If FileExists( "c:\BookforTestData.csv ") Then
Kill "c:\BookforTestData.csv "
End If
Workbooks.Add
With ActiveSheet.QueryTables.Add(Connection:= "TEXT;E:\test.csv ", Destination _
:=Range( "A1 "))
.Name = "test "
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.TextFilePromptOnRefresh = False
.TextFilePlatform = 932
'这里我的cvs文件的编码是shift-jis.需要其他编码的代号可以自己录
.TextFileStartRow = 1
.TextFileParseType = xlDelimited
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = False
.TextFileTabDelimiter = True
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = True
.TextFileSpaceDelimiter = False
.TextFileColumnDataTypes = Array(1, 1, 1, 1)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With
ActiveWorkbook.SaveAs Filename:= "c:\BookforTestData.csv ", FileFormat:=xlCSV, _
CreateBackup:=False
ActiveWorkbook.Close SaveChanges:=True
Dim MyChar
Dim strText As String
Dim FileNum As Integer
Dim str() As String
Dim count As Integer
Dim count1 As Integer
count = 1
Open "c:\BookforTestData.csv " For Input As #1
Do While Not EOF(1)
Line Input #1, strText
str = Split(strText, ", ")
count1 = UBound(str)
For i = 0 To count1
Worksheets(1).Cells(i + 1, count).Value = str(i)
Next i
count = count + 1
Loop
Close #1
If FileExists( "c:\BookforTestData.csv ") Then
Kill "c:\BookforTestData.csv "
End If
End Sub
Private Function FileExists(fname) As Boolean
Dim x As String
x = Dir(fname)
If x <> " " Then FileExists = True _
Else FileExists = False
End Function