使用列的第一个单元格将特定列从一个工作表复制到另一个工作表

时间:2016-10-21 06:21:15

标签: vba excel-vba excel

我正在尝试根据ws22表格中的列标题复制ws22表格中的ws12表格列。

Sub secondprogram()

     Dim i As Integer
     Dim j As Integer
     For i = 1 To 3
         MsgBox i
         For j = 1 To 3
                     If Worksheets("ws22").Cells(1, i).Value = Worksheets("ws12").Cells(1, j).Value Then
                    'Worksheets("ws12").Range(Cells(2, j), Cells(10000, j)).Copy Destination:=Worksheets("ws22").Range(Cells(2, i), Cells(10000, i))
                     Worksheets("ws22").Range(Cells(2, i), Cells(10000, i)).Value = Worksheets("ws12").Range(Cells(2, j), Cells(10000, j)).Value
              End If
         Next j
     Next i
End Sub

当我使用msgbox时,正确的值即将来临。但代码显示错误运行时错误' 1004'两行中的应用程序定义或对象定义错误

 Worksheets("ws12").Range(Cells(2, j), Cells(10000, j)).Copy _
     Destination:=Worksheets("ws22").Range(Cells(2, i), Cells(10000, i))

 Worksheets("ws22").Range(Cells(2, i), Cells(10000, i)).Value = _
     Worksheets("ws12").Range(Cells(2, j), Cells(10000, j)).Value

2 个答案:

答案 0 :(得分:1)

在常规模块或ThisWorkBook中,每次使用不符合工作表的Range()Cells()都将默认使用ActiveSheet,因此最好确保始终符合条件。

因此,在下面的一行中,即使您符合Range()的条件,附带的Cells()也会引用活动表。

Worksheets("ws22").Range(Cells(2, i), Cells(10000, i)).Value = _
     Worksheets("ws12").Range(Cells(2, j), Cells(10000, j)).Value

要解决此问题,您需要更明确:

Dim ws22 As WorkSheet
Dim ws12 As worksheet

Set ws22 = Worksheets("ws22")
Set ws12 = Worksheets("ws12")

'....

ws22.Range(ws22.Cells(2, i), ws22.Cells(10000, i)).Value = _
     ws12.Range(ws12.Cells(2, j), ws12.Cells(10000, j)).Value

答案 1 :(得分:0)

通过对范围对象的这种引用,您需要重复工作表引用。试试这个:

 Worksheets("ws12").Range(Worksheets("ws12").Cells(2, j), Worksheets("ws12").Cells(10000, j)).Copy _
     Destination:=Worksheets("ws22").Range(Worksheets("ws22").Cells(2, i), Worksheets("ws22").Cells(10000, i))

或者更短一些:

With  Worksheets("ws12")
.Range(.Cells(2, j), .Cells(10000, j)).Copy _
     Destination:=Worksheets("ws22").Range(Worksheets("ws22").Cells(2, i), Worksheets("ws22").Cells(10000, i))
End with