VBA错误'方法范围…失败'(通过variables声明范围)

我在两张纸上find最后一行和最后一列,并将这些值分配给variables。 然后,我使用这些variables来形成一个范围的边界,将其放入一个VBA数组中。

为什么当我放置在与参考中使用的纸张不同的纸张上时,出现错误(对象“_Worksheet”失败的“方法范围”)? 我正在使用代号。

代码如下:

Private arrPlan() As Variant Private lastRowSource As Long Private lastColSource As Long Private arrRawData() As Variant Private lastRowDestination As Long Private lastColDestination As Long Private arrStrings() As Variant Private str As String Public Sub Google_Plan_Into_RawData() '------------------------ Read Excel ranges into Arrays ----------------- lastRowSource = Sheet1.Range("A" & Rows.count).End(xlUp).Row lastColSource = Sheet1.Range("A1").End(xlToRight).Column arrPlan = Sheet1.Range(Cells(1, 1), Cells(lastRowSource, lastColSource)) lastColDestination = Sheet2.Range("A1").End(xlToRight).Column lastRowDestination = Sheet2.Range("A" & Rows.count).End(xlUp).Row arrRawData = Sheet2.Range(Cells(1, 1), Cells(lastRowDestination, lastColDestination)) // ...Rest of the code 

它在这条线上失败:
arrPlan = Sheet1.Range(Cells(1, 1), Cells(lastRowSource, lastColSource))如果我在Sheet2上,当然,它在这一行失败:
arrRawData = Sheet2.Range(Cells(1, 1), Cells(lastRowDestination, lastColDestination))
如果我在Sheet1上。

我通常做的是:

 With Sheet1 lastRowSource = .Range("A" &Rows.count).End(xlUp).Row lastColSource= .Range("A1").End(xlToRight).Column arrPlan = .Range(Cells(1, 1), Cells(lastRowSource, lastColSource)) End With. 

仍然没有舔。 我在这里做错了什么?

尝试使用完整范围参考,包括工作表代号:

 arrPlan = Sheet1.Range(Sheet1.Cells(1, 1), Sheet1.Cells(lastRowSource, lastColSource)) arrRawData = Sheet2.Range(Sheet2.Cells(1, 1), Sheet2.Cells(lastRowDestination, lastColDestination)) 

尝试将工作簿和工作表的引用放在范围内:

 arrPlan = Range(Sheet1.Cells(1, 1), Sheet1.Cells(lastRowSource, lastColSource)) if 

第2页:

 arrRawData = Range(Sheet2.Cells(1, 1), Sheet2.Cells(lastRowDestination, lastColDestination))