【问题标题】:vba excel copy only visible cells on key press ctrl+c for protected sheetvba excel仅复制按键上的可见单元格 ctrl+c 用于受保护的工作表
【发布时间】:2026-01-25 08:55:01
【问题描述】:

我正在尝试替换 ctrl+c,以便它只复制受保护工作表上的可见单元格。试图解决这个问题我偶然发现了这篇文章(vba excel copy only visible cells on key press ctrl+c

以下代码(由 Siddharth-Rout 建议)有效,但仅适用于不受保护的工作表:

Private Sub Workbook_Open()
     Application.OnKey "^c", "Copy"
End Sub

Sub Copy()
    Dim rng As Range

    On Error GoTo Whoa

    If Not Selection Is Nothing Then
        Set rng = Selection.Cells.SpecialCells(xlCellTypeVisible)
        rng.Copy
    End If

LetsContinue:
    Exit Sub
Whoa:
    MsgBox Err.Description, vbCritical, "Error Number : " & Err.Number
    Resume LetsContinue
End Sub

我尝试取消保护、复制,然后重新保护,但它删除了副本。我需要保护最后一张纸。任何帮助将不胜感激。

【问题讨论】:

    标签: excel vba


    【解决方案1】:

    啊!过去的爆炸:P

    您需要在复制之前取消保护和保护。我也使用ActiveSheet 进行演示。如果需要,将其更改为相关工作表。

    这是你正在尝试的吗?

    Sub Copy()
        Dim rng As Range
        Dim MyPassword As String
    
        '~~> Change password as applicable
        MyPassword = "Sid"
    
        On Error GoTo Whoa
    
        If Not Selection Is Nothing Then
            ActiveSheet.Unprotect MyPassword
            Set rng = Selection.Cells.SpecialCells(xlCellTypeVisible)
            ActiveSheet.Protect MyPassword
    
            rng.Copy
        End If
    
    LetsContinue:
        Exit Sub
    Whoa:
        MsgBox Err.Description, vbCritical, "Error Number : " & Err.Number
        Resume LetsContinue
    End Sub
    

    【讨论】:

    • 有趣。 ActiveSheet.Unprotect/Protect 就像一个魅力,但 Worksheets("Example").Unprotect/Protect 给了我问题。非常感谢您的快速帮助!