问题
The code below ran earlier but will not execute when a cell is double clicked.
Private Sub Worksheet_DoubleClick(ByVal Target As range, Cancel As Boolean)
If Target.Font.Bold = False Then
Target.Font.Bold = True
Target.Font.Color = vbRed
Else
Target.Font.Bold = False
Target.Font.Color = 1
End If
End Sub
回答1:
Not an answer to why it's not working (@Mat's Mug and @Scott Craner beat me to that again), but a shortened version of the code.
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
With Target.Font
.Bold = Not .Bold
.Color = Choose(Abs(CLng(.Bold)) + 1, 1, vbRed)
End With
End Sub
Ok, not as easy to follow as the original but here's what it's doing:
Target.Font.Bold
is either TRUE or FALSE, so Not .Bold
will return the opposite.
Bold = TRUE so Not Bold = FALSE
Abs(CLng(.Bold)) + 1
Again, .Bold is either TRUE or FALSE. Numerically TRUE = -1, FALSE = 0.
CLNG(.Bold)
will return -1 or 0.ABS(CLNG(.Bold))
will return 1 or 0.Abs(CLng(.Bold)) + 1
will return 1 or 2 - which is used in the CHOOSE
command to return vbRed
or 1
.
回答2:
DO NOT type any of these signatures manually!
Use the code pane dropdowns instead:

Select Worksheet
from the left dropdown, and pick an event to handle in the right dropdown; the VBE will generate a method stub with the proper signature for you.
Typing them out manually off the top of your head can (and does!) result with handlers that end up never being called, or worse, that are called, but are given parameter values in the wrong arguments, e.g. if UserForm_QueryClose
is typed up manually with inverted parameters (the handler has 2 Integer
parameters, so you need to remember the exact order.. otherwise you assign Cancel
and the form understands that you assigned CloseMode
)
If you're not seeing Worksheet
in the left dropdown, then you're not in a worksheet's code-behind module. Worksheet events can only be handled in a worksheet module.
In a Workbook
module (i.e. ThisWorkbook
) you can handle the SheetBeforeDoubleClick
event to handle a double-click on any worksheet in the workbook:
Private Sub Workbook_SheetBeforeDoubleClick(ByVal Sh As Object, ByVal Target As Range, Cancel As Boolean)
End Sub
来源:https://stackoverflow.com/questions/44311489/why-wont-the-code-below-execute-when-a-cell-is-double-clicked-on