Dynamically adding values in several sheets with For..Next loop and Application.WorksheetFunction.HLookup

slayerpblade

New Member
Joined
Jun 9, 2014
Messages
2
Hi there,

I have this certain code that I need to implement. Basically I have to add values in several sheets based on hlookup. However, the names of the lookup tables in each sheet are worksheet-scoped and similar for scalability, and I have no idea how to implement the hlookup function in vba despite many attempts. The following is the code that I have so far:

Function TOTALSUM(SearchItem, SheetNameSubstring, LookUpTableName, LookUpColumn)
Dim AimRange
Dim temp
For Each Sheet In ThisWorkbook.Sheets
If InStr(1, Sheet.Name, SheetNameSubstring) <> 0 Then
AimRange = "'" & Sheet.Name & "'!" & LookUpTableName
Set temp = Application.WorksheetFunction.HLookup(SearchItem, Range(AimRange), LookUpColumn)
TOTALSUM = TOTALSUM + temp
End If
Next Sheet
End Function

Could anyone kindly point out to me what is wrong with my code? Thanks a lot!
 

Excel Facts

Shade all formula cells
To shade all formula cells: Home, Find & Select, Formulas to select all formulas. Then apply a light fill color.
Hi and Welcome to MrExcel,

Here's one way to write that.
If you are using HLookup instead of VLookup, you'll want to reference the LookUpRow instead of a LookUpColumn.

Code:
Function TOTALSUM(SearchItem, SheetNameSubstring, LookUpTableName, LookUpRow)
 Dim rAimRange As Range
 Dim vFound As Variant
 Dim wks As Worksheet
 
 Application.Volatile
 
 For Each wks In ThisWorkbook.Sheets
   If InStr(1, wks.Name, SheetNameSubstring) <> 0 Then
      Set rAimRange = wks.Range(LookUpTableName)
      vFound = Application.HLookup(SearchItem, rAimRange, LookUpRow, True)
      If IsNumeric(vFound) Then
         TOTALSUM = TOTALSUM + CDbl(vFound)
      End If
   End If
 Next wks
 End Function
 
Upvote 0

Forum statistics

Threads
1,223,243
Messages
6,170,967
Members
452,371
Latest member
Frana

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