简体   繁体   中英

VBA Excel-How to restrict users not to paste on specific rows?

I have an Excel like shown below which is a sharedExcel.

在此处输入图片说明

Now i should not allow paste option for the rows which have backcolour as GRAY (These are not fixed at runtime any row may get GRAY colour). As it sharedExcel and i can't use the Lock property. Any help wouls be appreciated greatly.

Using a color as a property that is used to check true / false is bad behaviour. You can get around this by for example adding a column (hidden if needed) with 0 / 1 or TRUE / FALSE which you make accessible by for example a combobox (then you can still adapt the color into gray by clicking this cbb box).

The you can check on a dynamically composed range via a Sheet event on_Change. The basic syntax for the sheet event:

Private Sub Worksheet_Change(ByVal Target As Range)
'Set range dynamically instead of this hard coded example 
If Not Intersect(Target, Thisworkbook.Sheets(1).Range("A1:A10")) Is Nothing Then 
    'Do something 
End If
End Sub

After spending some time on this problem i have coded following lines. It work's fine. Here i have taken another spreadsheet called PasteSheet for coding purpose but i am not showing it to user at any moment.


Private Sub Worksheet_SelectionChange(ByVal Target As Range)
If Application.CutCopyMode Then
    SelectedRow = ActiveCell.Row
    With Sheets("PasteSheet")
        .Activate
        .Range("A1").PasteSpecial xlPasteValues
        CR = Selection.Rows.Count
    End With
    Worksheets("ActualSheet").Activate
    For k = SelectedRow To (SelectedRow + CR)
        If Worksheets("ActualSheet").Cells(k, 30).Interior.Color = RGB(215, 215, 215) Then
            Application.EnableEvents = False
            MsgBox "Pasting is not allowed here!"
            'Clearing data in PasteSheet
            Worksheets("PasteSheet").Cells.ClearContents
            Worksheets("ActualSheet").Activate
            Application.EnableEvents = True
            Exit Sub
        End If
    Next
End If

End Sub

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