Search code examples
arraysvbaexcel

Values assigned to Array are stored as numbers, not as text


I'm populating an array from several columns. In one column there are sometimes numbers, letters or a combination of it. The numbers in the source are formatted as text. Meaning I have leading zero's. When the array is populated, it converts the text to numbers. This means I lose my leading zero's if applicable. But I need this.

What did I tried to so far:

  1. formatting the sheet where the array will post it to (will not work as the values in the array are already as numbers and lost the leading zero's);
  2. Changed Dim myArray() as Variant to Dim myArray() as String;
  3. Changed Dim i, j, k as Long to Dim i, j, k as String;
  4. use Cstr to store the data in the array as a string;

This is my code what I have now:

numberOfRecords = Range(Selection, Selection.End(xlDown)).Rows.Count + 1

Dim myArray() As String
Dim i, j, k As Long
k = 0
ReDim myArray(numberOfRecords, 2 To 6) As String

For i = 2 To numberOfRecords
    If IsError(Application.Match(Cells(i, "A").Value, 
        Sheets("SE16N").Range("A:A"), 0)) Then
            For j = 2 To 6
                myArray(k, j) = CStr(Cells(i, j).Text)
                Debug.Print myArray(k, j) 'Just to check how the array is storing data
            Next j
        k = k + 1
    End If
Next i

I hope someone can help me.

I can only post 2 links as I don't have a reputation of 10 yet at Stack Overflow. Therefore only to sure for sure I have leading zero's and with the local windows view.

With leading zero's Local Windows view


Solution

  • I found a way to go around this issue: I changed the format of the respective column to text manually which is a one time effort. Initially in my code I had range.clear, but now I use range.clearcontent. Clearcontent doesn't remove the formatting of the column. Now it works like a charm. :)