我想制作一段 VBA 代碼,將文本轉換為靈活的列,以適應 csv 檔案中的任意數量的列:
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
我嘗試了以下。在確定有多少列之后,我想使用一個變數“txt”來替換 FieldInfo 選項中的陣列宣告:
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 & ")"
對于 N=3,結果為: txt = "Array(Array(1, 1), Array(2, 1), Array(3, 1))" 但是,以下代碼給出了錯誤:
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
錯誤訊息是:“類 Range 的方法 TextToColumns 失敗”。
我怎樣才能解決這個問題?
uj5u.com熱心網友回復:
問題是您正在構建一個文本字串,其中包含構建陣列的命令,而不是實際的陣列。
以下函式可用于構建x元素陣列:
Function createarray(x As Long)
Dim arr, i As Long
ReDim arr(0 To x - 1)
For i = 0 To x - 1
arr(i) = Array(i 1, 1)
Next
createarray = arr
End Function
使用上面的,下面的命令:
FieldInfo:= Array(Array(1, 1), Array(2, 1), Array(3, 1))
可以換成:
FieldInfo:= createarray(3)
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/429219.html
