如何将工作表和范围作为变量传递?

How do I pass worksheet and ranges as variables?

我想在子例程之间传递工作表的名称和范围。以下引发 "Subscript out of range" 错误:

Sub This()

    x = "Sheet1"
    y = "D3"

    MsgBox (x.Range(y).Value)

End Sub

这是a sample of my Project Explorer。

您的工作表 .Name property is Valuation; its Worksheet .CodeName propertySheet1

dim x as string, y as string
dim xx as worksheet, yy as range

x = "Valuation"
set xx = worksheets(x)
y = "D3"
set yy = xx.range(y)
debug.print yy.address(0,0, external:=true)  '<~~returns Valuation!D3 (with the workbook name)

debug.print Sheet1.name    '<~~returns Valuation from CodeName