I have two sets of data in Excel, and I am trying to compare them in VBA. All the data is numeric (integers).
The "new" data is in a table, which gets copied over the "old" data as a range, and then the "new" data table gets updated.
Data format:
ID | Parameter_1 | Parameter_2 | Parameter_3 | etc.... |
---|---|---|---|---|
12345 | 3 | 7 | 9 | etc.... |
67890 | 1 | 2 | 3 | etc.... |
etc.... | etc.... | etc.... | etc.... | etc.... |
My code:
...
Sub sub1()
new_rows = ThisWorkbook.Sheets("new").Cells.SpecialCells(xlCellTypeLastCell).Row
old_rows = ThisWorkbook.Sheets("old").Cells.SpecialCells(xlCellTypeLastCell).Row
Dim new_data() As Variant
Dim old_data() As Variant
new_data = ThisWorkbook.Sheets("new").Range("A1:G" & new_rows).Value
old_data = ThisWorkbook.Sheets("old").Range("A1:G" & old_rows).Value
...
Dim update_tracker() As Variant
ReDim update_tracker(rows, columns)
...
updates_recorded = 0
For row_new = 2 To new_rows
ID = new_data(row_new, 1)
[code to match corresponding row in old_data that has same ID]
new_Parameter_1 = new_data(row_new, 4)
old_Parameter_1 = old_data(row_old, 4)
new_Parameter_2 = etc....
[all other data parameters]
If new_Parameter_1 <> old_Parameter_1 Then
update_tracker = track_updates(update_tracker, updates_recorded, ID, old_Parameter_1, new_Parameter_1, 1)
updates_recorded = updates_recorded + 1
End If
[if statements for all other parameters]
Next row_new
[irrelevant code to put data into Excel]
End Sub
Function track_updates(update_tracker, updates_recorded, ID, old_Parameter, new_Parameter, parameter_number)
If updates_recorded > 0 Then
ReDim Preserve update_tracker(start To UBound(update_tracker, 1), [same columns])
End If
update_tracker(UBound(update_tracker, 1), col_1) = ID
update_tracker(UBound(update_tracker, 1), col_2) = old_Parameter
update_tracker(UBound(update_tracker, 1), col_3) = new_Parameter
update_tracker(UBound(update_tracker, 1), col_4) = parameter_number
track_updates = update_tracker
End Function
An error comes up for the 4th line: "Type mismatch". This is regardless if the arrays are Integer
or Double
.
VarType([range].Value)
returns 8204
for both the new and the old ranges and the data is literally identical, yet the data can only be saved from the table into the first array.
If I Dim
all the arrays as Variant
then this part of the code works, but later when the ID
number is being saved to the update_tracker
the same error comes up.
Even though all 3 arrays are of type Variant
, putting ?VarType(ID)
into the "Immediate" window when debugging returns 5
, which indicates that the number is somehow saved as a Double
.
Using a different approach, from an answer I found on this site:
Dim old_data() As Variant
Dim r As Range
Set r = ThisWorkbook.Sheets("old").Range("A1:G" & old_rows)
old_data = r
results in the whole old_data
array just being full of zeros.
Please help!