You need to enable JavaScript to run this app. VBA Userform初始化时向Combobox填充系统字体的报错及空值问题
优惠活动
大模型
产品
解决方案
定价
更多

VBA Userform初始化时向Combobox填充系统字体的报错及空值问题

VBA 用户窗体加载系统字体到组合框的故障记录

基础需求

在用户窗体初始化时,将当前PC上所有可用字体填充到窗体的Combobox控件中。

初始运行故障

首次运行原始实现代码时直接触发运行时错误:
Run-time error '-2147467259 (80004005)': Method 'ListCount' of Object '_CommanBarComboBox' failed
当时尝试将循环初始值从i=1修改为i=0,问题没有解决。对应原始实现代码:

Private Sub UserForm_Initialize()
    Image3.Visible = False
    Image6.Visible = False

    Dim FontList
    Dim i
    CreatePapers.ComboBox1.Clear
    Set FontList = Application.CommandBars("Formatting").FindControl(ID:=1728)
    For i = 1 To FontList.ListCount
        CreatePapers.ComboBox1.AddItem FontList.List(i + 1)
    Next i
End Sub

第一次代码调整效果

调整代码逻辑后原有运行报错消失,但组合框没有填充任何内容。对应调整后的代码:

Dim FontList As CommandBarControl
Dim i As Long
Dim Tempbar As CommandBar
CreatePapers.ComboBox1.Clear

On Error Resume Next
Set FontList = Application.CommandBars("Formatting").FindControl(ID:=1728)
' 格式工具栏找不到内置字体控件时,新建临时命令栏承载控件
If FontList Is Nothing Then
    Set Tempbar = Application.CommandBars.Add
    Set FontList = Tempbar.Controls.Add(ID:=1728)
End If
    
For i = 1 To FontList.ListCount
    Debug.Print FontList.List(i)
    CreatePapers.ComboBox1.AddItem FontList.List(i)
Next i
Me.ComboBox1.ListIndex = 0

' 清理存在的临时命令栏
On Error Resume Next
Tempbar.Delete

后续迭代调整结果

  • 第二次调整:按照参考建议在上述代码中补充2行内容,组合框仍为空,无字体条目加载
  • 第三次调整:再次修正部分代码行,依然无法正常获取字体列表;哪怕执行到了If FontList Is Nothing对应的临时创建命令栏逻辑分支,FontList对象始终为空,没有获得有效控件引用。

内容的提问来源于stack exchange,提问作者Tomas Perlecky

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.24 10:36:02