简体   繁体   中英

VBA Text to Columns FieldInfo Text not working

Hi I am trying to create a code which converts column A to columns with a | delimiter and want column A to be in Text format.

My code:

Sub TEST_Text_to_Columns()
ActiveSheet.Range("A:A").Select
    Selection.TextToColumns _
      Destination:=Range("A1"), _
      DataType:=xlDelimited, _
      TextQualifier:=xlDoubleQuote, _
      ConsecutiveDelimiter:=False, _
      Tab:=False, _
      Semicolon:=False, _
      Comma:=False, _
      Space:=False, _
      Other:=True, _
      OtherChar:="|"
      FieldInfo _
    :=Array(1, 1), TrailingMinusNumbers:=True


ActiveSheet.Columns("A:GZ").AutoFit


End Sub

It doesn't seem to like this at the FieldInfo part.

Please help

You are missing the , _ after OtherChar line:

Sub TEST_Text_to_Columns()
ActiveSheet.Range("A:A").Select
    Selection.TextToColumns _
      Destination:=Range("A1"), _
      DataType:=xlDelimited, _
      TextQualifier:=xlDoubleQuote, _
      ConsecutiveDelimiter:=False, _
      Tab:=False, _
      Semicolon:=False, _
      Comma:=False, _
      Space:=False, _
      Other:=True, _
      OtherChar:="|", _
      FieldInfo _
    :=Array(1, 1), TrailingMinusNumbers:=True


ActiveSheet.Columns("A:GZ").AutoFit


End Sub

However, to also fix the rest of the code:

  • Select and selection are unnecessary, slow things down and can cause errors. There are articles in this forum as to how and why to avoid them.
  • To format a column as text, xlTextFormat returns a 2 , so your FieldInfo should be a bit different:

Sub TEST_Text_to_Columns()
ActiveSheet.Range("A:A").TextToColumns _
      Destination:=Range("A1"), _
      DataType:=xlDelimited, _
      TextQualifier:=xlDoubleQuote, _
      ConsecutiveDelimiter:=False, _
      Tab:=False, _
      Semicolon:=False, _
      Comma:=False, _
      Space:=False, _
      Other:=True, _
      OtherChar:="|", _
      FieldInfo _
    :=Array(1, 2), TrailingMinusNumbers:=True


ActiveSheet.Columns("A:GZ").AutoFit


End Sub

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