Excel 2010 VBA - 运行时错误1004 - 使用匹配将范围从一个工作表复制到另一个工作表

时间:2011-09-20 11:14:06

标签: excel vba

我无法看到我出错的地方

Dim Sheet1RowNumber As Variant, Sheet28RowNumber As Variant, sStaffName As String
sStaffName = Worksheets(1).Cells(7, 1).Value
Sheet28RowNumber = Application.Match(sStaffName, Worksheets(28).Range("a:a"), 0)
Sheet1RowNumber = Application.Match(sStaffName, Worksheets(1).Range("a:a"), 0)
Worksheets(1).Range(Cells(Sheet1RowNumber, 2), Cells(Sheet1RowNumber, 8)) =        Worksheets(28).Range(Cells(Sheet28RowNumber, 2), Cells(Sheet28RowNumber, 8))

1 个答案:

答案 0 :(得分:2)

当您从当前未选择/激活的工作表中引用多单元格范围时,VBA不喜欢它。 (奇怪的是,这不是单细胞范围的问题......)无论如何,这就是导致你的错误的原因。该陈述涉及两个不同表格上的多单元格范围:

Worksheets(1).Range(Cells(Sheet1RowNumber, 2), Cells(Sheet1RowNumber, 8)) = _ 
    Worksheets(28).Range(Cells(Sheet28RowNumber, 2), Cells(Sheet28RowNumber, 8))

您可以将要复制的范围存储在缓冲区(temp下方)中,将其拆分为两行。在每个语句之前,激活相应的表单。这有效:

Dim Sheet1RowNumber As Variant, Sheet28RowNumber As Variant, sStaffName As String
Dim temp As Variant

sStaffName = Worksheets(1).Cells(7, 1).Value
Sheet28RowNumber = Application.Match(sStaffName, Worksheets(2).Range("a:a"), 0)
Sheet1RowNumber = Application.Match(sStaffName, Worksheets(1).Range("a:a"), 0)

Worksheets(2).Activate
temp = Worksheets(2).Range(Cells(Sheet28RowNumber, 2), Cells(Sheet28RowNumber, 8))
Worksheets(1).Activate
Worksheets(1).Range(Cells(Sheet1RowNumber, 2), Cells(Sheet1RowNumber, 8)) = temp