VBA 用户窗体中所有控件的字体使用 For 循环

Font of all the controls in VBA Userform using For loop

The sample userform

我想要的是,当我按下一个按钮时,所有控件的字体都会更改为所需的值。我为下面的 commandbutton 写了这篇文章,它工作得很好。

Private Sub CommandButton2_Click()
CommandButton2.Font = "Arial"
End Sub

这很好用。但是当我尝试对同一应用程序使用 for 循环时,出现错误。我收到错误的片段是

Private Sub CommandButton2_Click()
Dim x As Control
CommandButton2.Font = "Arial"
For Each x In Me.Controls
    x.Font = "Arial"
Next
End Sub

错误:

'438: Object doesn't support this property or method'.

任何帮助将不胜感激。

如果你能确定所有的控件都有字体属性,那么只需将x.Font = "Arial"改为x.Font.Name = "Arial"

如果您有图像、滚动条、旋转按钮或其他没有字体的控件,您可以使用 IF 语句将它们过滤掉:

Private Sub CommandButton2_Click()
Dim x As Control
CommandButton2.Font = "Arial"
For Each x In Me.Controls
    If TypeName(x) <> "Image" And TypeName(x) <> "SpinButton" And TypeName(x).... Then
        x.Font.Name = "Arial"
    End If
Next
End Sub

或者您可以使用较少建议的 On Error Resume Next..

Private Sub CommandButton2_Click()
Dim x As Control
CommandButton2.Font = "Arial"
On Error Resume Next
For Each x In Me.Controls
    x.Font.Name = "Arial"
Next
On Error GoTo 0
End Sub