Index and Match array in VBA

Lefemmenikita

Board Regular
Joined
Jan 28, 2014
Messages
59
Office Version
  1. 2013
Platform
  1. Windows
Hi

I am dealing with thousands of rows of data.

I am trying to use the multiple criteria index and match in a VBA formula to return a result.

The formula I am currently using is:

Code:
Selection.FormulaArray ="=IF(RC[-3]=""Billable"",INDEX(Coding!C1:C5,MATCH(1,(Coding!C1=Data!RC11)*(Coding!C2=Data!RC1),0),3),INDEX(Coding!C1:C5,MATCH(1,(Coding!C1=Data!RC11)*(Coding!C2=Data!RC1),0),4))"
    Range("P2").Select
   
    Columns("P:P").Select
    Selection.Copy
    Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=False

This runs out of memory before cycling through all the cells in the column and returning a result

My question is:

Is there a way to make an index/match formula use a dynamic column reference? (therefore, eliminating the need to have an "if" statement in the above array formula)?

Also, is there a way to have an array index/match formula execute via VBA without running out of memory?

I am able to do this outside of VBA, though it takes around 5 mins for Excel to finish calculating the result before I am able to replace the formula with the calculated value.


Hope my question makes sense

Thanks
 
I just had a thought have you applied any filters to the sheets? because if you have then the code won't work properly, you must make sure that both sheets have the filters turned off or "all" selected on both
 
Upvote 0

Excel Facts

Fastest way to copy a worksheet?
Hold down the Ctrl key while dragging tab for Sheet1 to the right. Excel will make a copy of the worksheet.
Just tested it again after removing all autofilters from both pages.

Still getting the same result where the result only looks up to row 44 and everything else shows as 'not found'
 
Upvote 0
use the debugger and check what value you have got in the variable Lastdata. It would appear that you have gotthe number 43 in this variable.
How many rows of data have you got in column A of your DATA sheet ? 43?
as a temproray measusre change the line:
Code:
[COLOR=#333333]lastdata = .Cells(Rows.Count, "A").End(xlUp).Row[/COLOR]

to
Code:
Lastdata=200
and see whether you get 200 rows populated.
finally learn how to use the debugger and the locals window to work out what is going wrong yourself, because I am just guessing.
 
Last edited:
Upvote 0
Try changing this line as shown
Code:
 Next j
' write the results out
 Range(.Cells(1, 16), .Cells([COLOR=#ff0000]lastdata[/COLOR], 16)) = Results
End With
 
Upvote 0
Try changing this line as shown
Code:
 Next j
' write the results out
 Range(.Cells(1, 16), .Cells([COLOR=#ff0000]lastdata[/COLOR], 16)) = Results
End With

I was just coming here to post that I changed that part of the code and it worked!

Thank you
 
Upvote 0
use the debugger and check what value you have got in the variable Lastdata. It would appear that you have gotthe number 43 in this variable.
How many rows of data have you got in column A of your DATA sheet ? 43?
as a temproray measusre change the line:
Code:
[COLOR=#333333]lastdata = .Cells(Rows.Count, "A").End(xlUp).Row[/COLOR]

to
Code:
Lastdata=200
and see whether you get 200 rows populated.
finally learn how to use the debugger and the locals window to work out what is going wrong yourself, because I am just guessing.

Thanks for all your help! It is finally working how I want it to after I changed this part of the code:

Code:
' write the results out
 Range(.Cells(1, 16), .Cells(Lastdata, 16)) = Results
 
Upvote 0
I have been able to get this code to work for the most part with my own dataset. However, I am only getting the first 34 rows of data to return results. After that, I get "Not Found" still. In the debugger I see that LastData contains all rows of my data. From what I can tell, I think I am not iterating the rows correctly since my data is a slightly different setup.

My lookup is being done on the tab called "Measure Fields". Using the two columns GI and GN from Measure Fields, I need to match to columns A and B on "ValidMeasureDescriptions". The results I need are located in Col C.

Here is my current code:
VBA Code:
Sub Test()

Dim LastMeasureDesc, LastData, j, i As Integer
Dim Data, Results, MeasureDesc, One As Range


With Worksheets("ValidMeasureDescriptions")
 LastMeasureDesc = .Cells(Rows.Count, "A").End(xlUp).Row
 MeasureDesc = Range(Cells(1, 1), Cells(LastMeasureDesc, 3))
End With


With Worksheets("Measure Fields")
 LastData = .Cells(Rows.Count, "A").End(xlUp).Row
 Data = Range(.Cells(1, 1), .Cells(LastData, 198))
 
 
 Range(Cells(2, 198), Cells(LastData, 198)) = "Not found"
   Results = Range(.Cells(1, 198), .Cells(LastData, 198))


' I assume there is a header row so I start on row 2
For j = 2 To LastData
  For i = 2 To LastMeasureDesc
  
Debug.Print "MeasureDesctiption: " & (MeasureDesc(i, 1))
Debug.Print "Data: "; (Data(j, 191))

Debug.Print "MeasureDesctiption: " & (MeasureDesc(i, 2))
Debug.Print "Data: " & (Data(j, 196))

    If MeasureDesc(i, 1) = Data(j, 191) And MeasureDesc(i, 2) = Data(j, 196) Then
     ' code and description match so check billable
       Results(j, 1) = MeasureDesc(i, 3)
      End If
     Exit For
   Next i
 Next j
 
' write the results out
 Range(.Cells(1, 198), .Cells(LastData, 198)) = Results
End With
 
End Sub
 
Upvote 0
you are missing a number of "dots" in the code which might be the cause of your probelms. Also you have got some declarations which probably aren't what you intended
try this, I have annotated the code:
VBA Code:
Sub Test()

Dim LastMeasureDesc, LastData, j, i As Integer ' this line only defines I as an integer all the others will be variant

Dim Data, Results, MeasureDesc, One As Range ' ditto
' Note however that the code does work because VBA usually works perfectly Ok if everything is defined as variant

With Worksheets("ValidMeasureDescriptions")
 LastMeasureDesc = .Cells(Rows.Count, "A").End(xlUp).Row
 MeasureDesc = Range(.Cells(1, 1), .Cells(LastMeasureDesc, 3)) ' dots missing
End With


With Worksheets("Measure Fields")
 LastData = .Cells(Rows.Count, "A").End(xlUp).Row
 Data = Range(.Cells(1, 1), .Cells(LastData, 198))
 
 
 Range(.Cells(2, 198), .Cells(LastData, 198)) = "Not found"  ' Dots missing
   Results = Range(.Cells(1, 198), .Cells(LastData, 198))


' I assume there is a header row so I start on row 2
For j = 2 To LastData
  For i = 2 To LastMeasureDesc
  
Debug.Print "MeasureDesctiption: " & (MeasureDesc(i, 1))
Debug.Print "Data: "; (Data(j, 191))

Debug.Print "MeasureDesctiption: " & (MeasureDesc(i, 2))
Debug.Print "Data: " & (Data(j, 196))

    If MeasureDesc(i, 1) = Data(j, 191) And MeasureDesc(i, 2) = Data(j, 196) Then
     ' code and description match so check billable
       Results(j, 1) = MeasureDesc(i, 3)
      End If
     Exit For
   Next i
 Next j
 
' write the results out
 Range(.Cells(1, 198), .Cells(LastData, 198)) = Results
End With
 
End Sub
 
Upvote 0
I have used this new code and its still only matching the first set. As it is iterating the rows, I don't think it's iterating down the "ValidMeasureDescription" tab as it should. Using my debug.print I can see the following pair below doesn't match up. I would want to see Showerhead-Gas DHW-Joint HEA for both lines.

MeasureDesctiption: Advanced Power Strip-$10 Copay-Joint HEA
Data: Showerhead-Gas DHW-Joint HEA
 
Upvote 0
I have used this new code and its still only matching the first set. As it is iterating the rows, I don't think it's iterating down the "ValidMeasureDescription" tab as it should. Using my debug.print I can see the following pair below doesn't match up. I would want to see Showerhead-Gas DHW-Joint HEA for both lines.

MeasureDesctiption: Advanced Power Strip-$10 Copay-Joint HEA
Data: Showerhead-Gas DHW-Joint HEA
Here's a mini-sheet if that helps:
Book3.xlsx
ABCDEFGHIJKLMNOPQRSTUVWXYZAAABACADAEAFAGAHAIAJAKALAMANAOAPAQARASATAUAVAWAXAYAZBABBBCBDBEBFBGBHBIBJBKBLBMBNBOBPBQBRBSBTBUBVBWBXBYBZCACBCCCDCECFCGCHCICJCKCLCMCNCOCPCQCRCSCTCUCVCWCXCYCZDADBDCDDDEDFDGDHDIDJDKDLDMDNDODPDQDRDSDTDUDVDWDXDYDZEAEBECEDEEEFEGEHEIEJEKELEMENEOEPEQERESETEUEVEWEXEYEZFAFBFCFDFEFFFGFHFIFJFKFLFMFNFOFPFQFRFSFTFUFVFWFXFYFZGAGBGDGEGFGGGHGIGJGKGLGMGNGOGP
1Vendor Project IDMeasure DescriptionQuantityMeasure ID ICExternal Rebate Processor IDNicor Gas Tracking NumberIncentive NicorBuilder IncentiveRater IncentiveGross Annual Therm SavingsManufacturerModelSerialMeasure LifePost Installation EfficiencyPre Installation EfficiencyBaseline EfficiencyDerating baseDerating effEquipment Efficiency PercentN_HeatCapacity Existing EquipmentCapacity New EquipmentBaseline Production CapacityPre Install ValuePost Install ValueEquivalent Full Load HoursOperation Hours DayOperation Days YearAnnual Therm ConsumptionAs Built ThermsBase ThermsSizeHousehold FactorDegree of SetbackRestaurant TypeNumber of PansSavings FactorCalculation MethodTotal Sq Feet Above GradeTotal Sq Feet Below GradeThermal Regain FactorShowers Per Person Per DayHDDFraming Factor WallFraming Factor AtticAdjustment FactorR Value Existing Above groundR Value Existing Below groundLength of Faucet UseIn Service RateEnergy per GallonDeemed Therm SavingsLengthLength of Other ComponentsCircumference of PipeFurnace Heating LoadLbsDutyGriddle WidthGriddle DepthENERGY STAR Equipment Number of Preheats per DayBaseline Number of Preheats per DayENERGY STAR Preheat TimeBaseline Preheat TimeENERGY STAR Preheat RateBaseline Preheat RateENERGY STAR Idle Energy RateBaseline Idle Energy RateENERGY STAR Idle TimeBaseline Idle TimeASTM Energy to FoodEnergy Savings per PreheatΔ Daily Idle EnergyΔ Daily Preheat EnergyΔ Daily Cooking EnergyBare Pipe Heat LossInsulated Pipe Heat LossPercent Fossil FuelFaucets per HouseholdDrain FactorUtilization FactorUsageηDHWΔTHot Water Reduction FactorToutTinHeating ReductionSteam loss per TrapHeat of VaporizationLeaking and Blow-thruGallons per DayStandby LossU CoefficientγWaterAge of EquipmentLevel of Repairs CompletedExisting Unit StatusEquipment LocationInsulation MaterialIncentive Paid DateInstallation DatePurchase DateApproval DateAudit DateStart DateEnd DateTotal Measure Cost Labor MaterialsIncremental CostRebate Unit of MeasureSavings Unit of MeasureIncentive other utilityIncentive other non-utilityCustomer CostCustomer CopayEstimated RebateIncentive RateIncentive CapEstimated Installation CostEstimated Maintenance CostMaintenance CostEstimated Simple PaybackSimple PaybackEstimated Gross Annual Therm SavingsEstimated Annual Water SavingsAnnual Water SavingsEstimated Annual Sewer SavingsAnnual Sewer SavingsEstimated Gross kWh SavingsGross Annual kWh SavingsAs Built kWhBase kWhBlower Door Results ACH50Mechanical Ventilation Rate CFMMechanical Ventilation TypeSystem TypeSteam Trap TypeSteam System TypeNumber of Recommended ECMsConditioned BasementCalculated Delta Savings PercentMeasure NotesNumber of Scantrons ReturnedTeacher NameMini Grant AmountRetailer for Self-InstallBundle ComponentSub Contractor TypeHorsepowerPre Output CapacityPost Output CapacityMeasure Description DetailEfficiency of Heat RecoveryPipe Calculation MethodPipe MaterialsMeasure ApplicationPipe SizeInsulation SizeElbowsTeesFlangesValvesMeasure TypeMeasure Gross kWh SavingsMeasure Gross kW SavingsMeasure Level Water SavingsTotal Water SavingsTotal Gross kWh SavingsTotal Gross kW SavingsMeasure Fuel TypeCDDTotal Electric Heating PenaltyBulb_TypeReplaced_Bulb_WattInstalled_Bulb_WattNew_Freezer_TypeNew_Refrigerator_Product_CategoryExhaust_Fan_Usage_TypeExisting Duct ConditionPost Sealing Duct ConditionWeatherization_MaterialsPost Sealing Duct Condition2Weatherization MaterialsEquipment TypeOriginal Thermostat TypeLength of Pipe Insulation AddedIncentive_Nicor_PT__cLocation__cVendor_Measure_Name__cRecordTypeIdMeasure_Detail__cMeasure_Category__cEndOfImportColumnsValidatorsErrorsChange Measure Name
2WO-4152772Advanced Power Strip-$10 Copay-Joint HEA2a0P3u00000j2H88EAE53.400 Unknown1/17/20231/17/20231/17/2023$53.40$53.40UnitUnit$0.00$0.0010 DIMDirect Install2060.0232Electric Measure Name 1Not found
3WO-4152846Advanced Power Strip-$10 Copay-Joint HEA1a0P3u00000j1lvuEAA26.700 Unknown1/10/20231/10/20231/10/2023$26.70$26.70UnitUnit$0.00$0.0010 DIMDirect Install1030.0116Electric Measure Name 2Not found
4WO-4153001Advanced Power Strip-$10 Copay-Joint HEA2a0P3u00000j2FVOEA253.400 Unknown1/17/20231/17/20231/17/2023$53.40$53.40UnitUnit$0.00$0.0010 DIMDirect Install2060.0232Electric Measure Name 3DIMNot found
5WO-4153338Advanced Power Strip-$10 Copay-Joint HEA3a0P3u00000j2nKkEAI80.100 Unknown1/24/20231/24/20231/24/2023$80.10$80.10UnitUnit$0.00$0.0010 VADirect Install3090.0348Electric Measure Name 3VANot found
Measure Fields
 
Upvote 0

Forum statistics

Threads
1,214,386
Messages
6,119,214
Members
448,874
Latest member
b1step2far

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top