该宏用于锁定包含除当前日期以外的所有日期的列。我已经在每个工作表中对其进行了编码,并且在所有工作表中都完全相似。宏在任何单元格中的数据更改时运行。但是我希望宏在打开工作簿时运行。
我试图在“此工作簿”中对其进行编码,但是我不知道该怎么做。我也尝试在“模块”中执行此操作,但是无法。
Private Sub Worksheet_Change(ByVal Target As Excel.Range)
'vps
Dim x As Long
x = 7
ThisWorkbook.ActiveSheet.Unprotect Password:="123456"
ThisWorkbook.ActiveSheet.Cells.Locked = False
Do Until IsEmpty(Cells(5, x))
If Cells(5, x) <> Date Then
Columns(x).Locked = True
End If
x = x + 1
Loop
ThisWorkbook.ActiveSheet.Protect Password:="123456"
End Sub
我希望宏在打开工作簿时运行,而不仅仅是在单元格中的数据更改时运行。
答案 0 :(得分:0)
标准模块,例如Module1
Sub ProtectPrevious()
Const cRow As Long = 5 ' Date Row Number
Const cFirstC As Variant = 7 ' First Column Letter/Number e.g. 7 or "G"
Const cToday As Long = 6 ' Today Cell ColorIndex e.g. 6 is Yellow
Const cDays As Long = 15 ' Other Days ColorIndex e.g. 15 is some Gray
Dim ws As Worksheet ' Current Worksheet
Dim LastC As Long ' Last Column Number
Dim j As Integer ' Column Counter
For Each ws In ThisWorkbook.Worksheets
With ws
' Prepare for processing.
.Unprotect Password:="123456"
.Cells.Locked = False
' When there is no data in Date Row, continue with next worksheet.
If .Rows(cRow).Find("*", .Cells(cRow, _
.Columns.Count), -4123, , 1) Is Nothing Then Exit For
' Calculate Last Column Number
LastC = .Rows(cRow).Find("*", , -4123, , 1, 2).Column
' Remove formatting from other day(s) in Date Row.
With .Range(.Cells(cRow, cFirstC), .Cells(cRow, LastC))
.Interior.ColorIndex = cDays
End With
' Loop through columns: from First Column to Last Column.
For j = cFirstC To LastC
If .Cells(cRow, j) <> Date Then
.Columns(j).Locked = True
Else
' Apply formatting to 'today' in Date Row.
With .Cells(cRow, j)
.Interior.ColorIndex = cToday
End With
End If
Next
.Protect Password:="123456"
End With
Next
End Sub
此工作簿
Private Sub Workbook_Open()
ProtectPrevious
End Sub