簡體   English   中英

VBA 將用戶窗體放在所選范圍旁邊

[英]VBA Place Userform Next to Selected Range

我需要在選定的單元格旁邊放置一個用戶表單。 這是我的代碼。 Excel 2013.

在用戶表單模塊中:

Private rangePosition As Range 'Property passed to form to set position based on range

'Set userform position to right of range
Property Let PositionToRange(rangeInput As Range)
    Set rangePosition = rangeInput
    Me.Left = rangePosition.Left + rangePosition.Width + 30
    Me.Top = rangePosition.Top + Application.CommandBars("Ribbon").Height + 27
End Property

在標准模塊中:

userform.PositionToRange = Selection '(or some specified range)
userform.Show

好,太棒了。 所以起初這似乎可以解決問題。 但是,它似乎只在 Excel 第一次加載時在標准視圖中工作,前 30 行左右。 但是,如果您嘗試在第 4000 行甚至第 40 行使用它,它會將用戶窗體置於屏幕之外。 Excel 似乎沒有考慮屏幕的 position。 要明白我的意思,請嘗試使用上面的代碼在單元格 A1 旁邊放置一個用戶窗體。 然后向下滾動,使 A1 不再出現在屏幕上,然后再次運行代碼。 它將用戶窗體放在完全相同的位置,就好像您仍在原始 position 中向上滾動一樣。

除了range.Left等,我可以使用其他屬性來相對於屏幕上范圍的位置放置用戶窗體嗎? 或者我是否需要做一些奇怪的巫毒廢話,在計算出滾動條的 position 並找到與之相關的單元格的 position 之后,當然是在考慮了地球的自轉力和與太陽的相對距離之后?

哦,微軟...

您可以使用滾動條來調整表單滾動時的位置。

ActiveWindow.VisibleRange.Top &
ActiveWindow.VisibleRange.Left

使用它在所有情況下都可以使用

Me.Left = ActiveCell.Left + ActiveCell.Width  - ActiveWindow.VisibleRange.Left
Me.Top = ActiveCell.Top  - ActiveWindow.VisibleRange.Top

通過聲明GetDeviceCapsGetDCReleaseDC函數,我將用戶窗體重新定位到每個單擊的活動單元格旁邊。(模板已在 32 位和 64 位 Excel 版本中檢查)

Type POINTAPI
X As Long
Y As Long
End Type
#If VBA7 Then
Declare PtrSafe Function GetDeviceCaps Lib "gdi32" (ByVal hDc As LongPtr, ByVal nIndex As Long) As Long
Declare PtrSafe Function GetDC Lib "user32" (ByVal hwnd As LongPtr) As LongPtr
Declare PtrSafe Function ReleaseDC Lib "user32" (ByVal hwnd As LongPtr, ByVal hDc As LongPtr) As Long
Dim hDc As LongPtr
#Else
Declare Function GetDeviceCaps Lib "gdi32" (ByVal hDc As Long, ByVal nIndex As Long) As Long
Declare Function GetDC Lib "user32" (ByVal hwnd As Long) As Long
Declare Function ReleaseDC Lib "user32" (ByVal hwnd As Long, ByVal hDc As Long) As Long
Dim hDc As Long
#End If
...

在此處輸入圖像描述

源代碼,示例文件鏈接

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM