我知道如何使用以下方法保护工作表: -
Sub Protect()
Worksheets("Sheet1").Cells.Locked = False
Worksheets("Sheet1").Range("B1:b10").Locked = True
Worksheets("Sheet1").Protect Password:="erty", UserInterfaceOnly:=True
End Sub
我只想保护有文本的单元格。我的问题是列数会有所不同。如何计算列数并仅保护包含文本的单元格?
以下将实现您的期望:
Sub protectit()
Dim ws As Worksheet: Set ws = Sheets("Sheet1")
'declare and set the worksheet you are working with, amend as required
Dim c As Range
ws.Cells.Locked = False 'unlock all the cells in the given Sheet
For Each c In ws.UsedRange 'for each cell in UsedRange
If c.Value <> "" Then c.Locked = True 'if cell is not empty then locked = True
Next
ws.protect Password:="erty", UserInterfaceOnly:=True 'protect the populated cells
End Sub
如果有文字,您可以检查所有单元格并锁定它们:
Dim Cell As Range
For Each Cell in Sheet1.UsedRange
If Cell.Value <> "" Then Cell.Locked = True
Next Cell