我想通过VBA打开一个.csv文件,一些列格式化为文本。我的代码目前看起来像这样。
Workbooks.OpenText Filename:=vPath, Origin:=xlMSDOS, StartRow:=1 _
, DataType:=xlDelimited, TextQualifier:=xlTextQualifierDoubleQuote, ConsecutiveDelimiter:=True, semicolon:=True, local:=True, FieldInfo:=Array(Array(1, 2), Array(3, 2), Array(3, 2), Array(4, 2))
我使用local:=True
,因为我的关键语言是丹麦语,我不知道它是否会影响FieldInfo,还是我的代码还有其他问题?但是这些字段没有格式化为文本,而是格式化为General。
答案 0 :(得分:0)
您可以使用的另一种方法 - 逐行读取文件并按分隔符拆分。然后使用该数组预测数据所在的区域,并在添加值之前将该区域格式化为文本。
这是一个可以从文本文件中创建2D数组的UDF:
Function MM_OpenTextFile(vPath As String, delim As String) As Variant
Dim FF As Integer
Dim lineArray As Variant
Dim temp As String
Dim arrayList As Object
Set arrayList = CreateObject("System.Collections.ArrayList")
FF = FreeFile
Open vPath For Input As #FF
While Not EOF(FF)
Line Input #FF, temp
lineArray = Split(temp, delim)
arrayList.Add lineArray
Erase lineArray
Wend
Close #FF
MM_OpenTextFile = WorksheetFunction.Transpose(WorksheetFunction.Transpose(arrayList.ToArray()))
arrayList.Clear
Set arrayList = Nothing
End Function
以下是如何使用它的示例 - 将“A1”的引用更改为您选择的起始单元格。
Sub MM_Example_Use()
Dim ar As Variant '// Must be a Variant to work
'// Change to a file and delimiter of your choosing...
ar = MM_OpenTextFile("C:\Users\MacroMan\SomeFile.txt", ";")
With Range("A1").Resize(UBound(ar, 1), UBound(ar, 2))
.NumberFormat = "@" '// Change format to "text"
.value = ar '// insert array values
End With
End Sub