我从“通过信息搜寻和啄食来构建宏以提高在视频后期制作设施中完成的所有工作的效率”中猜测您对 VBA 的了解是有限的,并且您不知道哪些功能可能是相关的。这个答案是对我认为你需要的事件例程的介绍。
发生事件:打开或关闭工作簿、添加工作表、更改单元格值等。对于其中许多事件,您可以创建一个例程以在该事件发生时调用。
为了演示这些例程,我创建了一个工作簿和一个工作表“Work”。我已将 12 个单元格设置为数值并将 R12 设置为它们的总和。我已将范围 J2:O25 设置为数字 1 到 144。这是一个比您想要的更大的范围,但这对原理没有影响。
在下面的代码中,我使用了两个事件例程:Workbook_Open
和Workbook_SheetChange
.
在Workbook_Open
中,我保存了 R12 的原始值。在Workbook_SheetChange
,如果 R12 的值发生了变化,并且如果 J2:O25 包含新值,我将光标移动到它。
如果我理解您的问题,这就是您寻求的功能。如果没有,我希望这个答案能帮助你提出一个更好、更详细的问题。
您必须将此语句放在模块中:
Public R12Last As Variant
您必须将以下代码放置在ThisWorkbook
工作Microsoft Excel Objects
表下方。
Option Explicit
Sub Workbook_Open()
' This routine is called when the workbook is opened.
With Worksheets("Work")
' Save the value of cell R12 when the workbook opens.
R12Last = .Range("R12").Value
End With
End Sub
Private Sub Workbook_SheetChange(ByVal WSht As Object, ByVal ChgRng As Range)
' This routine is called when cells in any worksheet are changed by the
' user or by an external link.
' WSht is the worksheet within which cells have changed.
' ChgRng can be a single cell or a range.
' For this application, we are not interested in the cell that has changed.
' We want to know if the change affected R12.
Dim SearchRng As Range
Dim FoundRng As Range
With Worksheets("Work")
If R12Last <> .Range("R12").Value Then
' Cell R12 has changed
R12Last = .Range("R12").Value ' Record the new value for next time
' I have a larger range containing the values that might be in R12
' but the principle is the same. You will need to change this to M31:M40.
Set SearchRng = .Range("J2:O25")
' Look for the new value of R12 in SearchRng.
' "What" is the value to be found. "After" must be within the search
' range. "After" is the last cell to be searched. I have set
' SearchDirection to xlNext and SearchOrder to xlByRows so the Find will
' check cells starting with J2.
' Look Find up in VBA Help for a fuller description.
Set FoundRng = SearchRng.Find(What:=R12Last, After:=Range("O25"), _
LookIn:=xlValues, LookAt:=xlWhole, _
SearchOrder:=xlByRows, _
SearchDirection:=xlNext)
If FoundRng Is Nothing Then
' The value of R12 has not been found in the search range.
' Add code to handle this situation
Call MsgBox("Target value not found", vbOKOnly)
Else
' Make the cell with the matching value the active cell.
FoundRng.Select
End If
End If
End With
End Sub