您的位置:首页 > 编程语言 > VB

vba中读取utf-8格式的csv文件保证不乱码

2009-11-01 16:46 2775 查看
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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐