简体   繁体   中英

Excel VBA: Locking range of cells

Im trying to lock a few ranges of cells to prevent them from being altered outside of the button press. I have the following code so far:

Private Sub DateRangePayer()

Dim unionRange As Range, uRng As Range, EssentialWrite As Range, chCell As Range, chRng As Range
Dim d As Long, k As Long, x As Long

ActiveSheet.Unprotect

Set EssentialWrite = Sheets("Essential Info").Range("E2:E6")
Set unionRange = ActiveSheet.Range("Q8:R12, T8:T12, Q16:R20, T16:T20")
Set chRng = ActiveSheet.Range("Q8:R12, T8:T12, Q16:R20, T16:T20")

x = Sheets("Essential Info").Range("G19").Value
ReDim OArr(1 To 5, 1 To 1) As Variant

For d = DateSerial(Year(x), Month(x), 1) To DateSerial(Year(x), Month(x) + 1, 0) - 1
    If Weekday(d, vbSunday) = 7 Then
        k = k + 1
        OArr(k, 1) = d
    End If
Next d

If k = 4 Then OArr(k + 1, 1) = "-"

For Each uRng In unionRange.Areas
    uRng.Value = OArr
    uRng.NumberFormat = "dd-mmmm"
Next uRng

For Each chCell In chRng.Cells
    chCell.MergeArea.Locked = (chCell.Value <> "")
Next chCell

EssentialWrite.Value = OArr
EssentialWrite.NumberFormat = "dd-mmmm"

ActiveSheet.Protect


End Sub

The main parts of the code are the

ActiveSheet.Unprotect


For Each chCell In chRng.Cells
chCell.MergeArea.Locked = (chCell.Value <> "") Next chCell


ActiveSheet.Protect

Currently the code executes with zero errors. However the range of cells is not locked at all and is actually editable in its entirety. Im doing this to prevent unexpected user entries in the specified cells Any advice on what may work.

Im sorry if the code is a little messy. Im kinda just hacking together at this point and relatively new to this

This code locks only the code that say LOCKED in the image below.

Sub lockCells()

    Dim ws As Worksheet
    Set ws = Sheets("Sheet1")

    ws.Cells.Locked = False

    Dim rng As Range
    Set rng = ws.Range("A1:A10")

    Dim cell As Range

    For Each cell In rng
        cell.Locked = cell.Value <> ""
    Next cell

    ws.Protect 1234
End Sub

在此处输入图片说明

我不确定这是“最佳做法”,但我会使用:

chCell.Cells(1, 1).Locked = (chCell.Value <> "")

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