简体   繁体   中英

VBA to paste data on the cells without changing format

I have a Macro-enabled protected workbook where the user is allowed to edit only a certain fields or rows(150 to 200) on all sheets.

The concern is I am not able to set the formatting on the editable fields, so when the user copy anything on the fields it takes the source format and it clutters the sheet.

I tried to use the following but that didn't help. Please suggest.

Private Sub Workbook_SheetSelectionChange(ByVal Sh As Object, ByVal Target As Range)
    On Error Resume Next
    Target.PasteSpecial xlPasteValues
    Application.CutCopyMode = True
End Sub

Give this a shot:

Option Explicit 

Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)

    If Target.Row >= 150 And Target.Row <= 200 Then 

        Dim vNewValues as Variant
        NewValues = Target

        Application.EnableEvents = False
        Application.Undo

        Target = NewValues

        Application.EnableEvents = true

  End If

End Sub

It works by storing the new values (those copied or entered into the cells) into an array, then performing an undo, which will erase the operation (and any undesired formatting), then places only the values (from the stored array) into the range.

The If condition may need tweaking based on your actual requirements.

Range.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks

应该只复制值,而不复制初始范围内的格式。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM