为每个单击的ActiveCell定位Userform

时间:2014-07-11 14:25:37

标签: excel vba excel-vba position cell

我有一个MonthView和DTPicker的UserForm,当点击某些单元格时,它将填充。我将表单定位在第一个单元格的正下方,但是希望它在我告诉它激活的每个活动单元格下面填充。我当前用于定位用户表单的激活代码是:

Private Sub UserForm_Activate()
    With frmCalendar
        .Top = Application.Top + 340
        .Left = Application.Left + 330
    End With
End Sub

和我的工作表选择更改代码,它将在某些单元格单击时启动用户窗体:

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    If Not Application.Intersect(Target, Range("H10,H15")) Is Nothing Then
        frmCalendar.Show
    End If
End Sub

我知道有些插件有助于实现这一点,但我想知道如何在不使用添加的情况下将用户表单放在上面提到的单元格下方(H10,H14,H15) -在。我是否需要将代码添加到工作表子或激活子?那是什么代码?

感谢。

编辑:

我刚刚将Activate Sub代码更改为

Private Sub UserForm_Activate()
With frmCalendar
    .Top = ActiveCell.offset(31).Top
    .Left = ActiveCell.offset(1).Left
End With

End Sub

这会稍微向下移动并略微向右移动单元格,但是当我在另一个单元格上尝试它时实际上是向下移动但向右移动的距离相同。这仍然是凌乱的。使用这些方法无法将此表单直接放在ActiveCell下面?

4 个答案:

答案 0 :(得分:2)

您正在使用正确的事件宏。我在工作表中放置了一个TextBox并使用此宏

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    Dim s As Shape
    Set s = ActiveSheet.Shapes(1)
    s.Top = ActiveCell.Offset(1, 1).Top
    s.Left = ActiveCell.Offset(1, 1).Left
End Sub

我可以让TextBox向右移动,就在活动单元的正下方。

答案 1 :(得分:0)

我找到了http://www.vbaexpress.com/forum/archive/index.php/t-22038.html并开发了我用过的:

Sub showUform(iRow&, iCol&)
  Dim x11!, y11!
  ActiveSheet.Cells(iRow, iCol).Select
  x11 = ActiveWindow.PointsToScreenPixelsX(ActiveSheet.Cells(1, 1))
  y11 = ActiveWindow.PointsToScreenPixelsY(ActiveSheet.Cells(1, 1))
  UserForm1.Left = x11 + ActiveSheet.Cells(iRow, iCol).Left
  UserForm1.Top = y11 + ActiveSheet.Cells(iRow, iCol).Top
  UserForm1.Show
End Sub

答案 2 :(得分:0)

Sub FormToActCell(UF As Object, Optional RaD$ = "ACAD", Optional Topw% = 102, _
                  Optional TopH% = -120)
' form to Active cell or RaD as range address ,offsets topW topH
  Dim Px&, Py&, Zoomp!

  If RaD = "ACAD" Then RaD = ActiveCell.Address

  Set CellToRange = Range(RaD)

  With CellToRange    ' get point about object to
    Px = (.Left + .Width * Topw / 100)
    Py = (.Top + .Height * TopH / 100)
  End With
  Zoomp = ActiveWindow.Zoom / 100
  With UF  ' assuming screen as normal pts to pix of 3:4
    .Left = Px * Zoomp + ActiveWindow.PointsToScreenPixelsX(0) * 0.75
    .Top = Py * Zoomp + ActiveWindow.PointsToScreenPixelsY(0) * 0.75
  End With
End Sub

答案 3 :(得分:0)

请参阅我提供给这个问题的答案,因为我相信这个问题是一样的。

How do I properly align UserForm next to active cell