confusion123
Active Member
- Joined
- Jul 27, 2014
- Messages
- 400
In the code below, is there any reason why these are declared twice, once in the Sub and once in the Function?
Could they not been declared once only at the top of the module?
Rich (BB code):
Dim objLoan As Loan
Dim objLoans As Collection
Could they not been declared once only at the top of the module?
Rich (BB code):
Sub TestCollectionObject()
Dim rg As Range
Dim objLoans As Collection
Dim objLoan As Loan
Set rg = ThisWorkbook.Worksheets("Loans"). _
Range("LoanListStart").Offset(1, 0)
' get the collection of loan objects
Set objLoans = CollectLoanObjects(rg)
Debug.Print "There are " & objLoans.Count & _
" loans."
' iterate through each loan
For Each objLoan In objLoans
Debug.Print "Loan Number " & objLoan.LoanNumber & _
" has a payment of " & Format(objLoan.Payment, "Currency")
Next
Set objLoans = Nothing
Set objLoan = Nothing
Set rg = Nothing
End Sub
Function CollectLoanObjects(rg As Range) As Collection
Dim objLoan As Loan
Dim objLoans As Collection
Set objLoans = New Collection
' loop until we find an empty row
Do Until IsEmpty(rg)
Set objLoan = New Loan
With objLoan
.LoanNumber = rg.Value
.Term = rg.Offset(0, 1).Value
.InterestRate = rg.Offset(0, 2).Value
.PrincipalAmount = rg.Offset(0, 3).Value
End With
' add the current loan to the collection
objLoans.Add objLoan, CStr(objLoan.LoanNumber)
' move to next row
Set rg = rg.Offset(1, 0)
Loop
Set objLoan = Nothing
Set CollectLoanObjects = objLoans
Set objLoans = Nothing
End Function
Last edited: