设置范围时未设置对象变量或带块变量

时间:2020-03-24 07:49:10

标签: excel vba

我有一个链接的单元格,它会根据滚动条更改值。

我想获取E列中单元格的值,而行#将取决于滚动条链接的单元格值。

示例:如果链接的单元格值为2,我想获取单元格E3的值。

我得到了

对象变量或未设置块变量

我在这里阅读线程,但没有帮助。

Sub getweekrowindexrange()
Application.ScreenUpdating = False
Set wsCalculations = Sheets("Calculations")
'Set wsDashboard = Sheets("Dashboard")
Dim weekrowindex As Long
Dim Dashboardweekrange As Range

'this line works fine, gives me the value i need    
weekrowindex = WorksheetFunction.Sum(wsCalculations.Range("BS1").Value, 1)

'this gives me the 'Object variable or With block variable not set' error.
'i tried adding 'Set' before the Dashboardweekrange variable
' but then i get an 'Object required' message
Dashboardweekrange = wsCalculations.Range("E" & weekrowindex).Value

MsgBox weekrowindex 'ignore this line, i just use it to test the index value
End Sub

我的数据的屏幕截图。我隐藏了列,以避免任何人感到困惑。
worksheet

2 个答案:

答案 0 :(得分:1)

尝试:

Sub test()

    'Dashboardweekrange is a range
    Dim Dashboardweekrange As Range

    Set Dashboardweekrange = wsCalculations.Range("E" & weekrowindex)

    'Dashboardweekrange is a long
    Dim Dashboardweekrange As Long

    Dashboardweekrange = wsCalculations.Range("E" & weekrowindex).Value

End Sub

答案 1 :(得分:0)

wsCalculations.Range(“ E”&weekrowindex).Value获取范围的单元格值,而不是范围本身。因此,设置Dashboardweekrange = wsCalculations.Range(“ E”&weekrowindex)。 –

非常感谢@AxelRichter !!!!