I want to make a piece of VBA code that converts text to columns flexible to any number of columns in a csv file:
Selection.TextToColumns Destination:=Range("A1"), DataType:=xlDelimited, TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=False, _
Semicolon:=True, Comma:=False, Space:=False, Other:=False, FieldInfo:=Array(Array(1, 1), Array(2, 1), Array(3, 1)), TrailingMinusNumbers:=True
I tried the following. After determining how may columns there are I want to use a variable 'txt' that replaces the Array declaration in the FieldInfo option:
txt1 = "Array("
txt2 = ", 1)"
txt3 = ", "
For i = 1 To N
If i < N Then h = txt1 & i & txt2 & txt3
If i = N Then h = txt1 & i & txt2
txt = txt & h
Next i
txt = txt1 & txt & ")"
For N=3 this results into: txt = "Array(Array(1, 1), Array(2, 1), Array(3, 1))" However, the following code gives an error:
Selection.TextToColumns Destination:=Range("A1"), DataType:=xlDelimited, TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=False, _
Semicolon:=True, Comma:=False, Space:=False, Other:=False, FieldInfo:=txt, TrailingMinusNumbers:=True
The error message is: "Method TextToColumns of class Range has failed".
How can I fix this?