【发布时间】:2019-05-18 05:31:24
【问题描述】:
我已将拖放功能添加到嵌套在我的 Excel 用户窗体中的框架控件内的图像控件中。
我试图阻止嵌套的图像控件移出父控件。
如果位置超出父控件的范围,我正在考虑在 BeforeDropOrPaste 事件中使用 IF 语句来退出所有正在运行的宏(因此也是 mousemove 事件)。
如何比较控件的放置位置和父控件的范围?
我认为代码会是什么样子。
Private x_offset%, y_offset%
Private Sub Image1_BeforeDropOrPaste(ByVal Cancel As MSForms.ReturnBoolean, ByVal Action As MSForms.fmAction, ByVal Data As MSForms.DataObject, ByVal X As Single, ByVal Y As Single, ByVal Effect As MSForms.ReturnEffect, ByVal Shift As Integer)
Dim X as Range
Dim Y as Range
Set x = parent control range
Set y = the drop location of the control this code is in
'If Y is outside or intersects X then
End
Else
End Sub
Private Sub Image1_MouseDown(ByVal Button As Integer, ByVal Shift As Integer, _
ByVal X As Single, ByVal Y As Single)
If Button = XlMouseButton.xlPrimaryButton Then
x_offset = X
y_offset = Y
End If
End Sub
Private Sub Image1_MouseMove(ByVal Button As Integer, ByVal Shift As Integer, _
ByVal X As Single, ByVal Y As Single)
If Button = XlMouseButton.xlPrimaryButton Then
Image1.Left = Image1.Left + X - x_offset
Image1.Top = Image1.Top + Y - y_offset
End If
End Sub
如果嵌套控件的位置超出或与父控件范围相交,则将嵌套控件返回到它在 MouseMove 事件之前所在的位置。
编辑 - 如果控件对象重叠,我发现此代码使用函数返回真值。 http://www.vbaexpress.com/forum/showthread.php?33829-Solved-finding-if-two-controls-overlap
Function Overlap(aCtrl As Object, bCtrl As Object) As Boolean
Dim hOverlap As Boolean, vOverlap As Boolean
hOverlap = (bCtrl.Left - aCtrl.Width < aCtrl.Left) And (aCtrl.Left < bCtrl.Left + bCtrl.Width)
vOverlap = (bCtrl.Top - aCtrl.Height < aCtrl.Top) And (aCtrl.Top < bCtrl.Top + bCtrl.Height)
Overlap = hOverlap And vOverlap
End Function
例如,当 Frame 控件称为“Frame1”而 Image 控件称为“Image1”时,这如何工作?
【问题讨论】: