使用从函数返回的范围的Excel VBA

时间:2015-01-25 18:21:04

标签: excel vba excel-vba

我有这个函数返回一个Range:

Private Function getInvestorsCompanyRange()
    Dim companyStart As range
    Dim lastRow As range
    If Len(Trim(investorsCompanyRange.value)) = 0 Then
             getInvestorsCompanyRange = range("A1")
    Else
            Set lastRow = investorsCompanyRange.End(xlDown)
             getInvestorsCompanyRange = range(investorsCompanyRange, lastRow)
    End If
End Function

这个函数用于根据我的表单中的组合框从该范围中获取正确的值:

Private Sub cmbNoteName_Change()
    Dim investorsRange As range
    Set investorsRange = getInvestorsCompanyRange

    lblNoteCompany.Caption = investorsNameRange.Rows.Offset(cmbNoteName.ListIndex).value
End Sub

我一直需要获取对象..我知道getInvestorsCompanyRange返回正确的范围,因为当我尝试将其分配给组合框列表时 - 它显示正确的值。

1 个答案:

答案 0 :(得分:0)

您没有使用Set从函数中指定返回值:没有Set(并且因为您没有指定函数的返回类型),您将返回范围而不是范围本身。

Private Function getInvestorsCompanyRange() As Range
    Dim companyStart As range
    Dim lastRow As range
    If Len(Trim(investorsCompanyRange.value)) = 0 Then
            Set getInvestorsCompanyRange = Range("A1")
    Else
            Set lastRow = investorsCompanyRange.End(xlDown)
            Set getInvestorsCompanyRange = Range(investorsCompanyRange, lastRow)
    End If
End Function