Excel文本文件连接TextFileColumnDataTypes

时间:2016-12-08 14:46:14

标签: arrays excel excel-vba connection flat-file vba

我在Excel中连接的TextFileColumnDataTypes参数中使用的数组存在问题。

我在下面的代码中发表了评论,因此您可以看到有问题的行。这不是我正在使用的完整代码,但错误是相同的,这是它本质上已经煮熟了所以有些东西可能看起来有点粗糙,因为我已经将它们硬编码到这个例子中。

Sub TestWhyStuffBreaks()
Dim xlApp As Excel.Application, xlWb As Excel.Workbook, xlSht As Excel.Worksheet, i As Integer, arrDT() As Integer

Set xlApp = CreateObject("Excel.Application")
Set xlWb = xlApp.Workbooks.Add

ReDim arrDT(16)
For i = 1 To 16
    arrDT(i) = 2
Next i

xlApp.Visible = True

Set xlSht = xlWb.Sheets(1)

With xlSht.QueryTables.Add(Connection:="TEXT;C:\temp\textfile.txt", Destination:=xlSht.Range("$A$1"))
    .Name = xlSht.Name
    .FieldNames = True
    .RowNumbers = False
    .TextFilePlatform = 437
    .TextFileStartRow = 1
    .TextFileParseType = xlDelimited
    .TextFileTextQualifier = xlTextQualifierNone
    .TextFileConsecutiveDelimiter = False
    .TextFileOtherDelimiter = "|"
    .TextFileColumnDataTypes = arrDT 'This line errors with message of "Invalid procedure call or argument".
    '.TextFileColumnDataTypes = Array(2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2) 'This line is fine but not how I want to do it, I want to be able to dynamically change the length of the array.
    .Refresh BackgroundQuery:=False
End With

End Sub

在代码的完整版本中,数组的大小是不同的,因为它循环遍历超过1个文本文件,因此希望对它有动态。

在这种情况下Array(2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2)arrDT之间有什么区别?

2 个答案:

答案 0 :(得分:0)

所以,答案是将Option Base 1放在模块的顶部,或者从0到15循环。

与TextFileColumnDataTypes属性无关,只是我在数组中被废话!

答案 1 :(得分:0)

这完美无缺!

'Declare your Array as integer
Public Indices() As Integer
'with a loop set dimension
ReDim Indices(69)
'insert this line
.TextFileColumnDataTypes = Indices