vba paste values and keep source formatting?

只谈情不闲聊 提交于 2019-12-23 12:00:06

问题


I am trying to copy and paste some value from a column in one workbook to another:

Workbook 1

Column A
10/02/1990
41
11/01/2017
52

Workbook 2

Column I
10/02/1990
41
11/01/2017
52

The problem i am getting is if i simply copy my values from column 1 in workbook A and paste them to column I in workbook 2. then i get results like so:

Column I
34331
41
121092
52

This is because the formatting is somehow getting lost/confused by excel.

So i have created a button where users can paste this data using vba like so:

Sub Paste3()
Dim lastRow As Long
On Error GoTo ErrorHandler

lastRow = ActiveSheet.Range("H" & Rows.Count).End(xlUp).Row
ActiveSheet.Range("H10").PasteSpecial Paste:=xlPasteAllUsingSourceTheme, Operation:=xlNone, SkipBlanks:=False

Exit Sub

ErrorHandler:
MsgBox "Please Copy Values First."
End Sub

This works and the values keep their formatting. However, the cell format also changes.

What i mean by this is, the cells on workbook 1 have a black border, and the font is also black and bold.

I want to try and preserver workbook 2's font and cell border. This is:

Grey border, RGB(191, 191, 191) Grey Font (RGB 128, 128, 128) Font Size: 11 Font: Calibri

Essentially it needs to look like the column to the right.

I have tried this, but it doesn't work right, it adds borders to ranges in my spreadsheet it isn't supposed to.

Sub Paste3()
Dim lastRow As Long
On Error GoTo ErrorHandler

lastRow = ActiveSheet.Range("H" & Rows.Count).End(xlUp).Row
ActiveSheet.Range("H10").PasteSpecial Paste:=xlPasteAllUsingSourceTheme, Operation:=xlNone, SkipBlanks:=False

Dim rng As Range
Set rng = Range("H10:H" & lastRow)
With rng.Borders
        .LineStyle = xlContinuous
        .Color = RGB(191, 191, 191)
        .Weight = xlThin
        .Font
End With

With rng.Font
                .TextColor = RGB(128, 128, 128)
                .Font.Name = "Calibri"
                .Size = 11
                .Bold = False
            End With
Exit Sub

ErrorHandler:
MsgBox "Please Copy Values First."
End Sub

To be honest i would rather just find an easier way of pasting these values and keeping their format without changing the cell format and font colour etc.

Please can someone show me where i am going wrong?


回答1:


There's a PasteSpecial option for this:

ActiveSheet.Range("H10").PasteSpecial Paste:=xlPasteValuesAndNumberFormats, _
                 Operation:= xlNone, SkipBlanks:=False, Transpose:=False



回答2:


Instead of just try< Paste:=xlPasteAll> once



来源:https://stackoverflow.com/questions/41725730/vba-paste-values-and-keep-source-formatting

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!