VBA:从函数问题返回范围

时间:2014-08-06 15:27:16

标签: function vba parameters

我正在尝试清理我的代码,并且有一个片段用于查找最后一个单元格。这用于多个工作表。当我把它变成一个函数时,它似乎会导致错误。我相信它是我返回看似问题的范围的方式。我得到“需要对象”的运行时错误在下面的代码中,我试图通过捕获来自不同表的所有非空白单元格来创建数据透视表。如果有人有我错误的建议,我会非常感激吗?

Dim pt As PivotTable
Dim cacheOfPt As PivotCache 'this is the source data for the pt
Dim pf As PivotField
Dim pi As PivotItem 'pivot item are the values of a particular pivot feld
Dim myRange As Range
Dim wsPivot As Worksheet
Dim wsJournal As Worksheet

Set wsJournal = Worksheets("Sales_Journals")
Set myRange = myRangeFunc(wsJournal)

Worksheets.Add.Name = "UA.01.01 Breakdown per Product"
wsJournal.Select
Set cacheOfPt = ActiveWorkbook.PivotCaches.Create(xlDatabase, myRange.Address(0, 0))'<= this line is the issue

最后一个单元格的功能

Function myRangeFunc(ws As Worksheet) As Range


        On Error Resume Next
        With ws
            Set LastRow = Cells.Find("*", [A1], , , xlByRows, xlPrevious)
            Set lastCol = Cells.Find("*", [A1], , , xlByColumns, xlPrevious)
        End With

        If Not LastRow Is Nothing Then
            Set myRangeFunc = Range([A1], Cells(LastRow.Row, lastCol.Column))
            Debug.Print "Range is " & myRangeFunc.Address(0, 0)
        Else
            MsgBox "sheet is blank", vbCritical
        End If

End Function

1 个答案:

答案 0 :(得分:1)

Cells方法返回一个范围对象,其默认属性为.Value,所以当你这样做时:

Set myRangeFunc = Range([A1], Cells(LastRow.Row, lastCol.Column))

你实际上是这样做的:

Set myRangeFunc = Range([A1], Cells(LastRow.Row, lastCol.Column).Value)

总是会失败(除非该单元格包含有效的地址字符串,例如&#34; $ A $ 1&#34;等等。)

请改为:

Set myRangeFunc = Range([A1].Address, Cells(LastRow.Row, lastCol.Column).Address)

重新提出424错误,如果LastRowLastCol中的任何一个Nothing(即找不到数据),我希望如此。

稍微清理一下这个函数并正确声明你的变量,然后摆脱On Error Resume Next

Function myRangeFunc(ws As Worksheet) As Range
    Dim LastRow as Range, LastCol as Range
    Dim r as Long, c as Long

        With ws
            Set LastRow = Cells.Find("*", [A1], , , xlByRows, xlPrevious)
            Set lastCol = Cells.Find("*", [A1], , , xlByColumns, xlPrevious)
            If LastRow Is Nothing Then
                r = 1
            Else: r = LastRow.Row
            End If
            If LastCol Is Nothing Then
                c = 1
            Else: c = LastCol.Column
            End If

        End With


        Set myRangeFunc = Range("A1", Cells(r, c).Address)

        If LastRow Is Nothing And LastCol Is Nothing Then MsgBox "Sheet is blank!"

End Function