VBA粘贴sheet1值,并保持原始源格式?

时间:2019-01-16 02:24:49

标签: excel vba

我最多有6个单元,其潜在数据来自6个不同的地方。我正在尝试使用原始格式子Transfer_Data()

仅将前三个单元格的数据传输到另一张表中。
Sub Transfer_Data()

Dim i As Long, j As Long

j = 1

For i = 1 To 6
    If Sheets("Sheet1").Cells(i, 1).Value <> "" Then
        Sheets("Sheet2").Cells(j, 1).Value = Sheets("Sheet1").Cells(i, 1).Value
        j = j + 1
    End If

    If j > 3 Then Exit For
Next i

End Sub

发生什么事,当我试图保留sheet1时会显示sheet2的格式和颜色

1 个答案:

答案 0 :(得分:0)

像这样尝试...

Sub Transfer_Data()

Dim i As Long, j As Long

j = 1

For i = 1 To 6
    If Sheets("Sheet1").Cells(i, 1).Value <> "" Then
        Sheets("Sheet1").Cells(i, 1).Copy
        Sheets("Sheet2").Cells(j, 1).PasteSpecial xlPasteFormats
        Sheets("Sheet2").Cells(j, 1).PasteSpecial xlPasteValues
        j = j + 1
    End If

    If j > 3 Then Exit For
Next i
Application.CutCopyMode = False
End Sub

根据新要求编辑了代码:

Sub Transfer_Data()

Dim i As Long, j As Long

j = 1

For i = 1 To 6
    If Sheets("Sheet1").Cells(i, 1).Value <> "" Then
        Sheets("Sheet2").Cells(j, 1).Value = Sheets("Sheet1").Cells(i, 1).Value
        Sheets("Sheet2").Cells(j, 1).Interior.Color = Sheets("Sheet1").Cells(i, 1).Interior.Color
        j = j + 1
    End If

    If j > 3 Then Exit For
Next i

End Sub