我需要帮助才能在鼠标左键单击时捕获单元格值。因此,当用户在特定单元格中单击鼠标左键时,我需要在VBA代码中捕获该特定单元格值(在该单元格中写入的值)。
然后,该值将传递给VBA代码,并且不同单元格中的单击输出将不同。我希望我能够解释目的。
我总共有10个单元格,用于捕获鼠标左键单击值。
答案 0 :(得分:2)
此代码将检查是否一次选择多个单元格,然后检查该单元格是否为空。如果它是空的则退出,否则它存储值为单元格N1。您可以更改值存储的单元格。如果N1有一个值,它将转到N列中的下一个空单元格。
Dim oval
Dim N As Long
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
If Target.Cells.Count < 2 Then
If Target = Empty Then
Exit Sub
End If
oval = Target.Value
MsgBox "The value saved is " + oval + "."
If Range("N1").Value = "" Then
N = 1
Else
N = Cells(Rows.Count, "N").End(xlUp).Row + 1
End If
Cells(N, "N").Value = oval
End If
End Sub
答案 1 :(得分:1)
如果你愿意点击鼠标双击,你可以试试
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
MsgBox Target.Value
Cancel = True
End Sub
答案 2 :(得分:0)
这个怎么样?只是写了它,如果您单击可以用键盘触及的地方,它将不会注册鼠标单击
在工作表代码下输入:
XXXXXXX
Option Explicit
Private prevTarget As Range
Private Sub Worksheet_Activate()
Set prevTarget = Selection
End Sub
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Dim wasMouseClick As Boolean
Dim ch1, ch2, ch3, ch4, ch5, ch6, ch7, ch8, ch9 As String
On Error Resume Next
ch1 = prevTarget.Offset(1, 0).Address
ch2 = prevTarget.Offset(-1, 0).Address
ch3 = prevTarget.Offset(0, 1).Address
ch4 = prevTarget.Offset(0, -1).Address
ch5 = prevTarget.End(xlDown).Address
ch6 = prevTarget.End(xlToLeft).Address
ch7 = prevTarget.End(xlToRight).Address
ch8 = prevTarget.End(xlUp).Address
On Error GoTo error_noPreTarget
If Not (Target.Address = ch1 Or _
Target.Address = ch2 Or _
Target.Address = ch3 Or _
Target.Address = ch4 Or _
Target.Address = ch5 Or _
Target.Address = ch6 Or _
Target.Address = ch7 Or _
Target.Address = ch8) Then
wasMouseClick = True
End If
Set prevTarget = ActiveCell
If wasMouseClick Then
Debug.Print wasMouseClick ' replace with what you want when wasMouseClick = True
End If
Exit Sub
error_noPreTarget:
Set prevTarget = Selection
End Sub