简体   繁体   中英

Font of all the controls in VBA Userform using For loop

The sample userform

All I want is, when I press a button, the font of all the controls is changed to a desired value. I wrote this for a commandbutton like below and it works fine for it.

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

This works fine. But when I try to use the for loop for the same application, I get error. The snippet in which I get error is

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

The error:

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

Any help will be greatly appreciated.

If you can be sure that all the controls have a Font property, then simply change x.Font = "Arial" to x.Font.Name = "Arial"

If you have Images, ScrollBars, Spinbuttons or other controls that don't have Font, you could filter them out with an IF statment:

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

Or you could use the lesser advised 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM