Excel VBA:为什么我无法从传递给函数的工作表中获取范围?

时间:2013-10-09 19:56:55

标签: excel-vba excel-2010 vba excel

我正在尝试使用辅助函数来获取范围以将其存储到变体中,但我遇到了一些问题。

首先,我只是尝试了以下内容:

Function GetRange(RangeLetter As String, Optional LastUniqueLine As Long = 1048576) As Varient
    Static LastUniqueLineStr As String
    If LastUniqueLineStr = "" Then
        LastUniqueLineStr = LastUniqueLine
    End If
    Set GetRange = Range(RangeLetter + "2:" + LastUniqueLineStr)
End Function

但这似乎不起作用。 Range()似乎超出了这里或其他的范围,所以我认为我必须通过工作表才能使其正常工作:

Function GetRange(RangeLetter As String, Optional LastUniqueLine As Long = 1048576, Optional ActiveSheet As Worksheet) As Variant
    Static LastUniqueLineStr As String
    Static CurrentSheet As Worksheet
    'If CurrentSheet = Nothing Then
    Set CurrentSheet = ActiveSheet
    'End If
    If LastUniqueLineStr = "" Then
        LastUniqueLineStr = LastUniqueLine
    End If
    Set GetRange = CurrentSheet.Range(RangeLetter + "2:" + LastUniqueLineStr) ' This is the line where I get the error.
End Function

这也不起作用。我收到以下错误:

Run-time error '1004':

Method 'Range' of object 'Worksheet' failed

当我打电话给我时,如何获得我想要的范围?

2 个答案:

答案 0 :(得分:1)

尝试:

GetRange = Range(RangeLetter + "2:" + RangeLetter + LastUniqueLineStr).Value

您错过了RangeLetter,导致地址格式错误。另外,使用.Value属性返回变体/数组,并省略Set关键字。

在符合CurrentSheet.Range...条件时,我仍然会在函数的上下文中没有ActiveSheet时收到错误,因此您可以将工作表作为变量传递:

Sub Test()
Dim var As Variant
var = GetRange(ActiveSheet, "A")
End Sub

Function GetRange(sh As Worksheet, RangeLetter As String, Optional LastUniqueLine As Long = 1048576, Optional ActiveSheet As Worksheet) As Variant
    Static LastUniqueLineStr As String
    Dim myRange As Range

    If LastUniqueLineStr = "" Then
        LastUniqueLineStr = LastUniqueLine
    End If

    Set myRange = sh.Range(RangeLetter + "2:" + RangeLetter + LastUniqueLineStr)

    GetRange = myRange.Value ' This is the line where I get the error.
End Function

答案 1 :(得分:1)

在我看来,错误就在您设置“GetRange”变量的行中。看起来.Range(RangeLetter +“2:”+ Last ....)的结果会创建一个地址为“a2:#”的范围,这将失败。该格式的范围需要为“a2:e7”或类似。您的范围参考必须是对称的。 “RC:RC”,“R:R”或“C:C”。希望有所帮助。