I am working with a Table in Excel, and would like to place data from 3 non-adjacent Table columns into an array. The array is then written to 3 columns (A:C) in a blank worksheet in a new workbook, which is saved as a text file.
The following code works when my table columns are adjacent to each other and arranged in the order I need them (achieved using helper columns).
Sub TblToTxtFile()
'PURPOSE: Create a txt file from the Excel table
Dim xWB As Workbook: Set xWB = ActiveWorkbook
Dim xNum As Long
Dim xArray As Variant
Dim xWBNew As Workbook
Dim xFileName As String: xFileName = xWB.Path & "\" & Left(xWB.Name, 6) & " Import.txt"
With xWB.Sheets("Entries").ListObjects("Entries Report")
xNum = .DataBodyRange.Rows.count
xArray = Union(.ListColumns("Account Number").DataBodyRange, .ListColumns("Amount2").DataBodyRange, .ListColumns("Item Description2").DataBodyRange).Value '2 in the column name indicates a helper column
End With
Set xWBNew = Workbooks.Add
With xWBNew.ActiveSheet
.Range("A1:A" & xNum).NumberFormat = "0" 'Keeps account number from being converted to scientific numbers
.Range("A1:C" & xNum) = xArray
End With
With xWBNew
.SaveAs FileName:=xFileName, FileFormat:=xlText, CreateBackup:=False
.Close savechanges:=False
End With
End Sub
In the final project re-arranging or adding helper columns to the table won't be an option, so I need a solution that doesn't require changes to the original table.
When I try to pull data from the unaltered table (the original columns in their original order) into the array, all 3 columns in the array are populated with data from the first column.