I am writing script/code/something to loop through each worksheet in the workbook and it is supposed to get the values from the worksheets that match the criteria. But when I run the function I do not get any value and when I have added MsgBox to see how far the code has gone it doesn't trigger.
I want the code to cycle through each worksheet and then gather the data as coded.
Anyone know what I am doing wrong? (Also I am new to Stackoverflow so if I need to improve my post in anyway please let me now!)
Function FindBelopp(Month As String, Typ As String) As Double
Dim rng As Range
Dim beloppColumn As Range
Dim lRow As Range
Dim firstAddress As Range
Dim ws As Worksheet
Dim rngAmount As Double
Dim ws_Count As Integer
Dim I As Integer
I = 1
ws_Count = Worksheets.Count
Do While I < ws_Count
Set ws = Worksheets(I)
If InStr(1, ws.Name, Month, 0) > 0 Then
With ws.Cells
Set beloppColumn = .Find("SEK", LookIn:=xlValues)
Set rng = .Find(Typ, LookIn:=xlValues, lookAt:=xlWhole)
If Not rng Is Nothing Then
Set firstAddress = rng
Do
If IsEmpty(rng.Offset(1, 0)) = True Then
Set lRow = Range(Cells(rng.Row, beloppColumn.Column), Cells(rng.End(xlDown)(0).Row, beloppColumn.Column))
Else
Set lRow = Range(Cells(rng.Row, beloppColumn.Column), Cells(rng.Row, beloppColumn.Column))
End If
If Application.Sum(lRow) > 0 Then
rngAmount = Application.Sum(lRow) + rngAmount
Else: End If
Set rng = .FindNext(rng)
Loop While rng.Address <> firstAddress.Address
Else: End If
End With
Else: End If
I = I + 1
Loop
FindBelopp = rngAmount
End Function
First of all. Thank you for the quick response and for teaching me something new. The issue was with .FindNext()
I made it work in a similar fashion and it might not be the most efficient use but incase of someone stumbling here with the same issue I thought I could add my now working code.
Function LoopThroughEachSheet(iWantMonths As String, iWantValues As String) As Double
Dim rng As Range
Dim firstAddress As Range
Dim moneyColumn As Range
Dim sumRows As Range
Dim lRow As Range
Dim Money As Double
Dim ws As Worksheet
For Each ws In Worksheets
If InStr(1, _
UCase(ws.Name), _
UCase(iWantMonths)) > 0 Then
With ws.Cells
Set rng = .Find(iWantValues, _
lookAt:=xlWhole, _
LookIn:=xlValues)
If Not rng Is Nothing Then
Set firstAddress = rng
Set moneyColumn = .Find("SEK", _
LookIn:=xlValues, _
lookAt:=xlWhole)
Do
With ws
Set lRow = rng.End(xlDown)(0)
If IsEmpty(rng.Offset(1, 0)) = True Then
Set sumRows = .Range(Cells(rng.Row, moneyColumn.Column).Address, _
Cells(lRow.Row, moneyColumn.Column).Address)
Else
Set sumRows = .Cells(rng.Row, moneyColumn.Column)
End If
End With
Money = Application.Sum(sumRows) + Money
Set rng = .Find(iWantValues, _
After:=rng, _
lookAt:=xlWhole, _
LookIn:=xlValues)
Loop While firstAddress.Address <> rng.Address
Else: End If
End With
Else: End If
Next
LoopThroughEachSheet = Money
End Function