我尝试使用this post中描述的OpenText
方法查看如下文件:
参考,AccNum,SCODE,RollNum
999,15697668,404040,4921817045040610
当我运行此代码时,第四列仍然以科学记数法出现:
Workbooks.OpenText FileName:="H:\DataFile.csv", Origin:=3, StartRow:=1, _
DataType:=1, TextQualifier:=1, ConsecutiveDelimiter:=False, _
Tab:=False, Semicolon:=False, Comma:=True, Space:=False, _
Other:=False, FieldInfo:=Array(Array(4, 2)), _
TrailingMinusNumbers:=True
你知道我做错了吗?
答案 0 :(得分:1)
这有效:
FieldInfo:=Array(Array(1, 1), Array(2, 1), Array(3, 1), Array(4, 2))
似乎你不能砍掉你不感兴趣的Array()
值。
答案 1 :(得分:0)
Excel会自动对大数字进行转换,但您可以通过以文本格式显示数字来解决此问题 此示例显示语法:
ThisWorkbook.Sheets(1).Columns(4).NumberFormat = "@"
答案 2 :(得分:0)
另一种方法是逐行读取csv,将其加载到多维数组中,并在字符串前添加撇号。
我测试了这个,我很肯定它有效。
Sub ReadLines()
Dim oFSO As FileSystemObject
Dim sLine As String
Dim vArray() As String
Dim vArray_Final As Variant
Dim oTS As TextStream
Dim iCols As Integer
Dim iRows As Integer
Dim lCnt As Long
Dim lCnt_X As Long
Dim lCnt_Y As Long
Set oFSO = New FileSystemObject
Set oTS = oFSO.OpenTextFile("U:\DataFile.csv")
lCnt_X = 1
lCnt_Y = 1
iCols = 4
Do Until oTS.AtEndOfStream
sLine = oTS.ReadLine
iRows = iRows + 1
Loop
Set oTS = Nothing
Set oTS = oFSO.OpenTextFile("U:\DataFile.csv")
ReDim vArray_Final(1 To iRows, 1 To iCols)
Do Until oTS.AtEndOfStream
lCnt = lCnt + 1
lCnt_X = 1
lCnt_Y = 1
sLine = oTS.ReadLine
vArray = Split(sLine, ",")
For lCnt_Y = 1 To iCols
vArray_Final(lCnt, lCnt_Y) = vArray(lCnt_Y - 1)
Next lCnt_Y
Loop
Set oTS = Nothing
Set oFSO = Nothing
For lCnt_X = 1 To iRows
For lCnt_Y = 1 To iCols
If lCnt_Y = iCols Then
ThisWorkbook.Sheets(3).Cells(lCnt_X, lCnt_Y).Value = "'" & vArray_Final(lCnt_X, lCnt_Y)
Else
ThisWorkbook.Sheets(3).Cells(lCnt_X, lCnt_Y).Value = vArray_Final(lCnt_X, lCnt_Y)
End If
Next lCnt_Y
Next lCnt_X
End Sub
答案 3 :(得分:0)
使用FieldInfo参数指定文本有效,除非它是.csv,在这种情况下,您只需将扩展名更改为.txt即可。出于某种原因,CSV文件会忽略此类信息。但是数组必须覆盖所有字段,而不仅仅是要导入的字段(跳过是其中一个选项。)