VBA-将特定单元格复制到新添加的数据

时间:2018-06-07 07:41:41

标签: excel vba excel-vba

以下是我用于向特定列添加数据的代码。 我希望能够遍历工作表中的范围,并将(A1:C1)范围的整个边框样式复制到新添加的数据。

Private Sub Add_Click()


Dim sh As Worksheet
Set sh = ThisWorkbook.Sheets("Sheet1")
Dim n As Long



n = sh.Range("A" & Application.Rows.Count).End(xlUp).Row

sh.Range("A" & n + 1).Value = Me.Id.Value
sh.Range("B" & n + 1).Value = Me.Title.Value
sh.Range("C" & n + 1).Value = Me.Sev.Value

2 个答案:

答案 0 :(得分:1)

你可以复制范围

sh.Range("A1:C1").Copy

并粘贴格式

sh.Range("A" & n+1 & ":C" & n+1).PasteSpecial Paste:=xlPasteFormats

答案 1 :(得分:0)

OP似乎没有问他们实际想要什么,并且对复制所有格式的答案感到满意,而不仅仅是边框。为了将来的读者,这里有一个复制 边框的方法。

Private Sub CopyBorders(rSrc As Range, rDst As Range)
    Dim BorderIndex As Long
    Dim i As Long
    If rSrc.Cells.Count <> rDst.Cells.Count Then Exit Sub
    For i = 1 To rSrc.Cells.Count
        For BorderIndex = 5 To 12
            ApplyBorder rSrc.Cells(i), rDst.Cells(i), BorderIndex
        Next
    Next
End Sub

Private Sub ApplyBorder(rSrc As Range, rDst As Range, BorderIndex As Long)
    Dim Bdr As Border
    Set Bdr = rSrc.Borders(BorderIndex)
    With rDst.Borders(BorderIndex)
        .LineStyle = Bdr.LineStyle
        If .LineStyle <> xlNone Then
            .Color = Bdr.Color
            .TintAndShade = Bdr.TintAndShade
            .Weight = Bdr.Weight
        End If
    End With
End Sub

Op会像这样称呼它

sh.Range("A" & n + 1).Value = Me.Id.Value
sh.Range("B" & n + 1).Value = Me.Title.Value
sh.Range("C" & n + 1).Value = Me.Sev.Value

'Copy Borders
CopyBorders sh.Range("A1:C1"), sh.Range("A" & n+1 & ":C" & n+1)