如何在选定的最后一行锁定单元格?

时间:2016-11-28 05:44:03

标签: excel-vba vba excel

Private Sub Worksheet_Change(ByVal Target As Range)

Dim lastRow As Long

lastRow = ActiveSheet.Cells(Rows.Count, "E").End(xlUp).Row

ActiveSheet.Unprotect
lastRow.Locked = True
ActiveSheet.Protect

End Sub

*我已经运行了这段代码。但仍然没有锁定最后一排。 *当添加" MsgBox lastrow"它的工作和显示正确的选定行。 *谢谢

打开此更多信息----> Excel View With Msg Box

1 个答案:

答案 0 :(得分:0)

如果列E中的单元格是合并单元格的一部分(在您的情况下合并了列E:K),那么您将一个带有变量Range的新MergedCell设置为合并区域,然后Lock整个合并单元格范围。

代码

Option Explicit

Private Sub Worksheet_Change(ByVal Target As Range)

Dim lastRow As Long, cell As Range, MergedCell As Range

' find last row in Column E
lastRow = ActiveSheet.Cells(Rows.Count, "E").End(xlUp).Row

ActiveSheet.Unprotect

Set cell = Range("E" & lastRow)

' if cell in Column E is part of merged cells
If cell.MergeCells = True Then
    Set MergedCell = cell.MergeArea
    MergedCell.Locked = True
Else
    cell.Locked = True
End If

ActiveSheet.Protect

End Sub