I have a worksheet with several columns. The first two columns are ID numbers that are treated as strings. These cells are formatted as General but the ID numbers are treated as text. For example the first field is 21 digits and may have leading zeroes. This is not my data; the data may have been inserted from an external application. (If you type in the same digits as what you see in the cell, it will be interpreted as an integer.)
I have written some VBA do some filtering of this data and ran into a problem. If I copy data from the source sheet to another sheet using a Copy operation, the data format is preserved. However, if I copy the data to a Variant array then later dump the entire array to a sheet, the ID numbers are converted to integers. I do not know if they are converted upon assigning to the array, or copying back out to the sheet.
Is it possible to preserve the nature of the ID numbers when copying to a Variant array? I have tried putting in a check for the cell format but that's not helpful because it's General.
A couple of other background notes:
1. The columns of data and data types can vary, so I can't hardcode the data types or formats. It has to be done dynamically.
2. The actual application identifies records with one particular field duplicated and puts them in one sheet, and records having that field unique and puts them in another sheet, so the source records are not contiguous. They have to be either Copy & Pasted one at a time, or accumulated in an array then dumped out. I am pursuing the latter to improve performance.
I have boiled down the code to the specific problem. Here is the code in the attached file. The state of the file is that the code has already been run.
Option Explicit
Public Sub Demo()
Dim ColCount As Long ' number of columns of data
Dim C As Long ' column number
' Copy headers to destination sheets
Worksheets("Raw Data").Rows(1).Copy WSRange.Rows(1)
Worksheets("Raw Data").Rows(1).Copy WSArray.Rows(1)
Dim ByArray() As Variant
' Copy to array then dump array to sheet
With Worksheets("Raw Data")
' Copy formats to destination sheets
.Cells.Copy
WSRange.Cells.PasteSpecial Paste:=xlPasteFormats
WSArray.Cells.PasteSpecial Paste:=xlPasteFormats
ColCount = .UsedRange.Columns.Count
ReDim ByArray(1 To 1, 1 To ColCount) As Variant
For C = 1 To ColCount
ByArray(1, C) = .Cells(2, C)
Next C
End With
With WSArray
.Range(.Cells(2, "A"), .Cells(2, ColCount)).Value = ByArray
End With
' Use Copy & Paste
Worksheets("Raw Data").Rows(2).Copy WSRange.Rows(2) ' allow for header row
End Sub
Bookmarks