使用块时无效或不合格的参考

时间:2015-06-30 16:31:43

标签: excel vba excel-vba

相关代码如下。基本上我将工作表设置为工作簿中的工作表。在with块中,我调用BuildProgressionArrays函数。当我尝试设置searchRange时,我收到无效或不合格的参考错误。如果我添加另一个Set Worksheet和With block,该函数可以正常工作。当我调用函数时为什么会丢失set工作表?

Set Worksheet = ThisWorkbook.Sheets("progression")
    totalResourcesStored = 1200
    With Worksheet
        For i = 1 To 10
            thisLevelTotalBuilt = 0
            ***BuildProgressionArrays (i)***
            Call BuildGenStoreAndPuzzleArrays
            thisLevelGen = GenRateArray(i - 1)
            thisLevelStorage = StorageAmountArray(i - 1)
            thisLevelPuzzleReward = PuzzleRewardArray(i - 1)
            thisLevelTotalToBuild = Application.Sum(ProgressionBuildNumArray)
            Do While thisLevelTotalBuilt < thisLevelTotalToBuild
                For k = LBound(ProgressionKeyArray) To UBound(ProgressionKeyArray)
                Next k
            Loop
        Next i
    End With



  Function BuildProgressionArrays(townHallLevel As Integer)
    ReDim ProgressionKeyArray(0)
    ReDim ProgressionBuildCostArray(0)
    ReDim ProgressionBuildTimeArray(0)
    ReDim ProgressionBuildNumArray(0)
    n = 0
    Set searchRange = .range("C9:C500")

1 个答案:

答案 0 :(得分:0)

该功能超出了sub的范围。您需要将工作表作为对象传递给它。

查看http://www.cpearson.com/excel/scope.aspx

尝试将功能代码更改为以下内容。

Function BuildProgressionArrays(townHallLevel As Integer,WS as WorkSheet)
ReDim ProgressionKeyArray(0)
ReDim ProgressionBuildCostArray(0)
ReDim ProgressionBuildTimeArray(0)
ReDim ProgressionBuildNumArray(0)
n = 0
Set searchRange = ws.range("C9:C500")

然后按以下方式调用它。

BuildProgressionArrays (i,Worksheet)