如何在运行时固定用户窗体高度?及按钮调窗高代码问题排查
Hey Joel, let's tackle your two UserForm issues one by one:
1. Setting a Fixed Height During UserForm Runtime
If you want to lock your UserForm's height so users can't adjust it while the form is open, you have two solid options:
Option 1: Disable Resizing Entirely (Easiest)
Open your UserForm in design view, press F4 to open the Properties window, and set the BorderStyle property to either:
fmBorderStyleFixedSingle: Users can't resize the form, but can still minimize/maximize (if those options are enabled)fmBorderStyleFixedDialog: Users can't resize or maximize the form—only close or minimize it
This locks the entire form's dimensions, including height, so dragging the edges won't change anything.
Option 2: Force Height to Stay Fixed
If you want users to adjust the form's width but keep the height locked, add this code to your UserForm's Resize event:
Private Sub UserForm_Resize() ' Replace 140 with your desired fixed height value Me.Height = 140 End Sub
Now whenever someone tries to drag the form to change its height, it will instantly snap back to your specified value.
2. Fixing the Toggle Height Button Code
Your original code has a syntax structure error that's stopping it from working as expected. Here's the corrected version, plus a simplified alternative:
Corrected Multi-Line Code
With Me If .Height <= 140 Then .Height = 280 ElseIf .Height >= 280 Then .Height = 140 End If End With
Simplified One-Liner
You can use VBA's IIf function to shorten the code while keeping the same logic:
With Me .Height = IIf(.Height <= 140, 280, 140) End With
Why Your Original Code Failed
- The
Ifstatement was structured incorrectly: you placed the assignment directly afterThenon a single line, then tried to follow it withElseIfwithout properly wrapping the condition block. VBA requires either a line break afterThen(for multi-line blocks) or a colon for single-line conditions (which doesn't pair well withElseIf). - A tiny note: While VBA is case-insensitive,
ElseIfis the standard capitalization—though that wasn't the root cause here.
内容的提问来源于Stack Exchange,提问作者Joel

