VBA如何在不使用.Select的情况下复制单元格内容

13

我正在编写一个可以将 Target 的单元格完全复制到另一个单元格的方法。该单元格是一个带有一些花哨格式的运输标签。是否有办法实现这一点?

最初我有这个:

Worksheets("Label").Range("A1").Value = Worksheets("Get Address").Range("A28").Value

对于纯文本它起作用了。 然而,我失去了我创建的样式,因为在第一行之后,它们是不同的:

enter image description here

我还尝试使用宏录制器,并且我使用了.Select获得了一个解决方案,我阅读了这篇文章以避免在可能的情况下不使用它。 我该怎么办?

' Created by the Macro Recorder
Range("A28:A33").Select
Range("A33").Activate
Selection.Copy
Sheets("Label").Select
Range("A1").Select
ActiveSheet.Paste

3
您的代码可以重写为一行:Range("A33").Copy Sheets("Label").Range("A1") - Santosh
1
+1 非常棒的地址示例。 - Gaijinhunter
3个回答

24
Worksheets("Get Address").Range("A33").Copy _
       Destination := Worksheets("Label").Range("A1")

7
要仅复制和粘贴数值,请使用以下方法:
Worksheets("Label").Range("A1").value = _
   Worksheets("Get Address").Range("A33").value

这个语句不会使用剪贴板。

0
您可以遍历范围中的每个单元格,复制并设置每个单元格的值、注释等到目标位置。这里是一个例子。
Sub CopySpecial(p_RangeFrom As String, p_OffsetRow As Integer, p_OffsetColumn As Integer)

    Dim l_Row As Integer
    Dim l_Column As Integer
    Dim thisCell As Range
    Dim l_TargetCell As Range

    l_Row = Range(p_RangeFrom).Row
    l_Column = Range(p_RangeFrom).Column

    For Each thisCell In Range(p_RangeFrom)

        Set l_TargetCell = Range(Cells(thisCell.Row + p_OffsetRow, thisCell.Column + p_OffsetColumn).Address)

        ' Copy the text
        l_TargetCell.Value = thisCell.Value

        ' Copy the comment only if we have a comment to copy
        If Not thisCell.Comment Is Nothing Then

            ' Delete any existing comment in the target cell, if any.
            ' If you don't to this the .AddComment Method below will fail.
            If Not l_TargetCell.Comment Is Nothing Then l_TargetCell.Comment.Delete
            Call l_TargetCell.AddComment(thisCell.Comment.Text)

        End If

        ' Add more items to copy here, such as color, etc.

    Next

End Sub

Sub TestCall()
    Call CopySpecial("A1:B2", 3, 3)
End Sub

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接