VBA将单元格值从一个工作表复制到另一个工作表

时间:2014-07-17 16:26:12

标签: excel vba

有没有人知道如何解决以下问题。我在表1中有一个表格,我想将其复制到表格2中。但是,只会对sheet1中第3行第11行到第32行不为空的单元格进行复制。 如果说C11不为空,则C11将被复制到E11,F11,H11,I11和J11。然后代码检查C12是否已填充并执行相同操作,依此类推。

复制的单元格放在第2行和第15列的sheet2中。我有以下代码可以很好地工作。然而,它复制了在sheet2中显然没有意义的公式,因此,值是无意义的:

Private Sub CommandButton1_Click()
Dim i As Integer
Dim a As Integer
a = 15
For i = 11 To 32
If Worksheets(1).Cells(i, 3) <> "" Then
Worksheets(1).Cells(i, 3).Copy Worksheets(2).Cells(a, 15)
Worksheets(1).Cells(i, 5).Copy Worksheets(2).Cells(a, 17)
Worksheets(1).Cells(i, 6).Copy Worksheets(2).Cells(a, 18)
Worksheets(1).Cells(i, 7).Copy Worksheets(2).Cells(a, 19)
Worksheets(1).Cells(i, 8).Copy Worksheets(2).Cells(a, 20)
Worksheets(1).Cells(i, 9).Copy Worksheets(2).Cells(a, 21)
a = a + 1
End If
Next i

如何调整代码才能仅复制值?

非常感谢您的支持。

2 个答案:

答案 0 :(得分:1)

    Dim i As Integer
    Dim rw As Range, rwD as Range

    Set rwD = Worksheets(2).Rows(15)

    For i = 11 To 32
        Set rw = Worksheets(1).Rows(i)
        If rw.Cells(3) <> "" Then

        rwD.Cells(15).Value = rw.Cells(3).Value
        rwD.Cells(17).Value = rw.Cells(5).Value
        rwD.Cells(18).Value = rw.Cells(6).Value
        rwD.Cells(19).Value = rw.Cells(7).Value
        rwD.Cells(20).Value = rw.Cells(8).Value
        rwD.Cells(21).Value = rw.Cells(9).Value

        Set rwD = rwD.Offset(1, 0)
        End If

    Next i

答案 1 :(得分:1)

因此,对代码进行最少更改的方法是:

Private Sub CommandButton1_Click()
Dim i As Integer
Dim a As Integer
a = 15
For i = 11 To 32
If Worksheets(1).Cells(i, 3) <> "" Then
Worksheets(2).Cells(a, 15) = Worksheets(1).Cells(i, 3).Value
Worksheets(2).Cells(a, 17) = Worksheets(1).Cells(i, 5).Value
Worksheets(2).Cells(a, 18) = Worksheets(1).Cells(i, 6).Value
Worksheets(2).Cells(a, 19) = Worksheets(1).Cells(i, 7).Value
Worksheets(2).Cells(a, 20) = Worksheets(1).Cells(i, 8).Value
Worksheets(2).Cells(a, 21) = Worksheets(1).Cells(i, 9).Value
a = a + 1
End If
Next i