tags:

views:

20

answers:

2

I got the following simple functions:

Public Function AddFields(field1 As Range, field2 As Range) As String
    AddFields = "=" + field1.Address + "+" + field2.Address
End Function


Private Function GetCustomerCount(monthNumber As Integer) As Range
    If monthNumber < 6 Then
        GetCustomerCount = Range("D13")
    ElseIf monthNumber < 12 Then
        GetCustomerCount = Range("D14")
    Else
        GetCustomerCount = Range("D15")
    End If
End Function

Which I call from the following sub:

Private Sub mDateLooper_OnMonth(looper As DateLooper)
    Cells(looper.Row, looper.Column).Value = "Månad " & CStr(looper.MonthIndex + 1)
    Cells(looper.Row + 1, looper.Column).Value = AddFields(GetCustomerCount(looper.MonthIndex + 1), Range("m21"))
    Cells(looper.Row + 2, looper.Column).Value = AddFields(Cells(looper.Row + 1, looper.Column - 1), Cells(looper.Row, looper.Column))
End Sub

It doesn't work. I get the following error: Object variable or with block not set.

on GetCustomerCount = Range("D13").

Why?

A: 

I believe you need to identify which sheet the Range applies to, i.e. ActiveSheet.Range("D13")

Lazarus
+2  A: 

GetCustomerCount is a Range

If you want to assign it a new Value / Range you need to do this with set.

    Set GetCustomerCount = Range("D13")
marg
In Tools->Options you might want to enable "Require Variable Declaration" - it's a little inconvenient at first but makes sure you have all your ducks in a row before you start getting weird errors.What Marg mentioned is an easily-forgettable convention of VBA: "normal variables" such as integers, longs, and strings are normally assigned with i = 4 or userName = "John Smith". Anything else, ranges, worksheets, etc., are objects and need to use they keyword "Set" as in Marg's example.
Michael