我正在使用 VBA 构建 Excel 2016 用户窗体,需要收集打开窗体的单元格的行和列。我使用 Worksheet_BeforeDoubleClick
在单元格上双击打开表单,然后使用 UserForm_Initialize()
初始化用户表单。我想将双击事件的 Target
传递给 UserForm_Initialize()
但我不确定如何传递。 This forum thread解决了这个问题,但提供的解决方案对我不起作用。
这是我的Worksheet_BeforeDoubleClick
:
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
Column = Target.Column
Row = Target.Row
'Find the last non-blank cell in column B(2)
lRow = Cells(Rows.Count, 2).End(xlDown).Row
'Find the last non-blank cell in row 2
lCol = Cells(2, Columns.Count).End(xlToRight).Column
If Not Intersect(Target, Range(Cells(3, 3), Cells(lRow, lCol))) Is Nothing Then
Cancel = True
EdgeEntryForm.Show
End If
End Sub
还有我的UserForm_Initialize()
:
Private Sub UserForm_Initialize()
Dim Column As Long, Row As Long 'I would like to fill these with the Target values
MsgBox ("Row is " & Row & " Column is " & Column)
'Description.Caption = "Fill out this form to define a network edge from " & Cells(2, Row).Value & " to " & Cells(Column, 2).Value
End Sub
最佳答案
正如我在评论中所建议的那样,一种方法是只使用 ActiveCell
并将其分配给一个变量。
或者,如果您确实想将它作为变量传递,您可以通过一些变通方法来实现,即使用一个全局变量来临时保存该信息:
在您的工作表代码中:
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
'.....
With UserForm1
Set .rngTarget = Target
.Show
End With
'.....
End Sub
在您的用户表单中:
Public rngTarget As Range
Private Sub UserForm_Activate()
'....
If Not rngTarget Is Nothing Then
MsgBox ("Row is " & rngTarget.Row & " Column is " & rngTarget.Column)
Else
MsgBox "something went wrong with assigning rngTarget variable"
End If
'....
End Sub
编辑:我最初试图提出类似于@MathieuGuindon 的 answer 的建议。 ,但由于我对初始化和激活之间的区别了解有限而失败了(感谢 Mathieu)。
我更新了答案以在用户窗体级别使用全局变量,而不是使用模块中的全局变量。
关于Excel VBA : Pass `Target` Variable from Click Event to Userform,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56528036/