简体   繁体   中英

Dynamically format columns on Workbook.OpenText using FieldInfo in VBA

I'm writing a program in VBA to open a text file. I want to format the cells to text on open to perserve data (issue: long number strings are being converted to numbers and truncate).

Through research I've learned this can be done using the FieldInfo argument for .OpenText .

All current examples working on the internet are static and require the programmer to hard code in FieldInfo:=Array(Array(1,2),Array(2,2).....Array(n,2) .

Here is the closest I got to an answer but this doesn't work either. http://www.excelforum.com/excel-general/522433-workbooks-opentext-method-fieldinfo-parameter.html . It gives me a 1004 error. Here is my version:

Dim colInfo(1 To 1000,1 To 2)
For i = 1 To 1000
    colInfo(i , 1) = i
    colInfo(i , 2) = 2
Next i

I can't find any vba documentation on Array . If I could figure out how to create an Array variable NOT a Dim x() As y , I could solve this issue. Any help would be greatly appreciated!

The Array function just returns a variant - it is just a quick way of initialising. So you could just create one of those instead and pass that in as your argument. For example:

Sub abc()

Dim v1 As Variant, v2 As Variant

v1 = Array(1, 2, 3)

ReDim v2(3)
v2(0) = 1
v2(1) = 2
v2(2) = 3

MsgBox v1(0) & vbTab & v2(0) & vbCr & v1(1) & vbTab & v2(1) & vbCr & v1(2) & vbTab & v2(2)

End Sub

These two arrays (v1 and v2) are the same.

I hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM