Excel vba 控件随窗体大小改变

请教各位,Excel vba ,不是VB,网上搜出来的都是VB。
在运行窗体情况下,怎么可以做到控件随窗体大小改变而改变,也是窗体里面的内容可以跟着大小变化?

img

img

Option Explicit

Private Const GWL_STYLE = (-16)

Private Const WS_THICKFRAME = &H40000
Private Const WS_MINIMIZEBOX = &H20000
Private Const WS_MAXIMIZEBOX = &H10000

Private Declare Function GetWindowLong Lib "user32" Alias _
    "GetWindowLongA" (ByVal hwnd As Long, ByVal nIndex As Long) As Long

Private Declare Function SetWindowLong Lib "user32" Alias _
    "SetWindowLongA" (ByVal hwnd As Long, ByVal nIndex As Long, _
    ByVal dwNewLong As Long) As Long
    
Private Declare Function GetForegroundWindow Lib "user32" () As Long

Private Sub UserForm_Resize()
    On Error Resume Next
    
    With TextBox1
        .Left = 0
        .Height = Me.InsideHeight
        .Width = Me.InsideWidth
        .Top = 0
    End With
End Sub


Private Sub UserForm_Initialize()
    Me.Show
    Dim lngWndStyle As Long
    lngWndStyle = GetWindowLong(GetForegroundWindow(), GWL_STYLE)
    lngWndStyle = lngWndStyle Or WS_THICKFRAME Or WS_MINIMIZEBOX Or WS_MAXIMIZEBOX
    SetWindowLong GetForegroundWindow(), GWL_STYLE, lngWndStyle
    Call UserForm_Resize
End Sub

码字不易,如果对你有启发和帮助,请采纳! 答案参考Chatgpt解答

在Excel VBA中,要实现控件随窗体大小改变而改变大小,可以通过使用事件处理程序来实现。下面是一个简单的示例,演示了如何在运行时调整按钮控件的大小以适应窗体的大小变化:

  1. 打开Excel,并在VBA编辑器中打开相应的用户窗体(UserForm)。
  2. 在用户窗体的代码模块中添加以下代码:
Private Sub UserForm_Resize()
    ' 在窗体大小变化时触发的事件处理程序
    ' 可根据需要调整其他控件的大小和位置

    ' 调整按钮控件的大小
    CommandButton1.Width = Me.Width * 0.8
    CommandButton1.Height = Me.Height * 0.5
    CommandButton1.Left = (Me.Width - CommandButton1.Width) / 2
    CommandButton1.Top = (Me.Height - CommandButton1.Height) / 2
End Sub

在上述示例中,UserForm_Resize 是窗体的大小变化事件处理程序。每当窗体的大小发生变化时,该事件将被触发。

在事件处理程序中,我们根据窗体的新大小调整了按钮控件 CommandButton1 的宽度、高度、左边距和上边距。通过乘以比例因子(例如0.8和0.5),可以根据窗体的大小来确定新的控件尺寸。