简体   繁体   English

使用 vba 锁定单元格

[英]Lock a cell using vba

How to lock a cell using VBA?如何使用 VBA 锁定单元? I saw to lock cells you need protect the sheet, but it lock all cells I want lock 1 cell my code我看到要锁定您需要保护工作表的单元格,但它锁定了所有单元格我想锁定 1 个单元格我的代码

Private Sub Workbook_Open()
    If Environ$("computername") = "09-PC-0154" Then PCdeposito = "F:" Else PCdeposito = "\\09-PC-0154"
    Ruta = Me.Path
    If Me.Name = Form62 Then
        Worksheets("Hoja1").bNuevo.Enabled = True
        Worksheets("Hoja1").Vale.Enabled = True
        Limpiar
    Else
        Worksheets("Hoja1").bNuevo.Enabled = False
        Worksheets("Hoja1").Vale.Enabled = False
        Worksheets("Hoja1").Range("H2").Locked = True
        NombreAnterior = Worksheets("Hoja1").Range("E11").Value
        Worksheets("Hoja1").Protect
    End If
    LeerArchivoFichas
    LeerArchivoAgentes
    LeerArchivoLegajos
    Worksheets("Hoja1").Range("A1").Select
End Sub

Idea is ask if Im opening a new book or an existing numered book想法是问我是打开一本新书还是一本现有的数字书

Anyway the relevant for this question is the Else part无论如何,与这个问题相关的是 Else 部分

I want lock cell H2 then lock it and next line protect the sheet我想要锁定单元格 H2 然后锁定它并下一行保护工作表

But then code stop with error as with protected sheet, later lines after the IF cant work (as those functions need write at other cells)但随后代码因受保护工作表的错误而停止,IF 后的后续行无法工作(因为这些函数需要在其他单元格中写入)

And if no protect the sheet, the line Worksheets("Hoja1").Range("H2").Locked = True has no effect and I can write at H2如果不保护工作表,则 Worksheets("Hoja1").Range("H2").Locked = True 行无效,我可以在 H2 处写入

(Also I suspect if protect the sheet, users cant write at other cells) (另外我怀疑如果保护工作表,用户不能在其他单元格写)

A cells 'locked' status does absolutely nothing - until the sheet is protected .单元格“锁定”状态绝对没有任何作用-直到工作表受到保护

By default, all cells are locked - but without protecting the sheet those locks are useless.默认情况下,所有单元格都被锁定 - 但如果不保护工作表,这些锁定是无用的。

But, when you protect a sheet, those locks take effect - meaning you're unable to alter those cells.但是,当您保护工作表时,这些锁就会生效——这意味着您无法更改这些单元格。

So if you unlock a cell, before protecting a sheet - just that cell is editable after protection is applied.因此,如果您在保护工作表之前解锁单元格 - 在应用保护后,该单元格是可编辑的。

So if you want to lock just one cell, the most straight-forward method is:因此,如果您只想锁定一个单元格,最直接的方法是:

  • remove sheet protection去除纸张保护
  • unlock all the sheet's cells解锁所有工作表的单元格
  • lock the cell that you want protected锁定要保护的单元格
  • apply sheet protection应用工作表保护

You can also dictate whether locked cells, unlocked cells or both can be selected - when applying your sheet protection.您还可以指定是否可以选择锁定单元格、未锁定单元格或两者都可以选择 - 在应用工作表保护时。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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