为何ListItem.ListSubitems无.BackColor属性?如何设置背景色?
问题解答:ListView子项设置背景色报错438的原因及解决方法
一、为什么ListSubItem没有BackColor属性?
微软提供的MSComctlLib.ListView控件中,ListSubItem对象本身不包含BackColor属性,这是控件的原生设计限制。该控件仅为ListItem(主项)提供了整行背景色设置的BackColor属性,子项仅支持通过ForeColor设置文字颜色,直接访问子项的BackColor会触发运行时错误438(对象不支持该属性或方法)。
二、设置子项背景色的可行方法
方法1:设置整行背景色(简单快速)
如果需求允许整行统一背景色,直接使用ListItem的BackColor属性即可,改动最小:
For i = 0 To FindAmountValue Set Li = List_UserForm.MainList.ListItems.Add(, , " ") ' 根据条件设置整行背景与文字色 If j >= FirstDate Then Li.BackColor = RawMaterialShelf_Position_Settings_System.Offset(List_System, 0).Value Li.ForeColor = RawMaterialShelf_Position_Settings_System.Offset(List_Font_System, 0).Value Else Li.BackColor = RawMaterialShelf_Position_Settings_System.Offset(List_Standard, 0).Value Li.ForeColor = RawMaterialShelf_Position_Settings_System.Offset(List_Font_Standard, 0).Value End If ' 添加子项并设置文字色 For j = 0 To Bundle_ID Li.ListSubItems.Add , , " " Li.ListSubItems(j + 1).ForeColor = Li.ForeColor Next Next
方法2:开启OwnerDraw手动绘制子项(精准控制单列)
如果必须单独设置某列子项的背景色,需要开启ListView的自绘模式,通过DrawItem事件手动绘制每个子项的背景和内容:
步骤1:开启自绘模式
在初始化代码中添加:
List_UserForm.MainList.OwnerDraw = True
步骤2:添加DrawItem事件处理代码
在UserForm的代码模块中添加以下事件过程:
Private Sub MainList_DrawItem(ByVal Index As Integer, ByVal rc As MSComctlLib.Rect, ByVal State As Integer) Dim li As ListItem Dim subItem As ListSubItem Dim colWidth As Integer Dim currentX As Integer Dim i As Integer Set li = MainList.ListItems(Index + 1) ' ListItems索引从1开始 ' 处理选中状态背景 MainList.DrawMode = dmNormal If State = lvwSelected Then MainList.FillColor = &H8000000D ' 系统默认选中色 Else MainList.FillColor = RawMaterialShelf_Position_Settings_System.Offset(List_Standard, 0).Value End If MainList.FillRect rc ' 绘制第一列主项 currentX = rc.Left colWidth = MainList.ColumnHeaders(1).Width MainList.ForeColor = li.ForeColor MainList.DrawText li.Text, currentX, rc.Top, colWidth, rc.Bottom - rc.Top, dtLeft Or dtVerticalCenter ' 绘制后续子项 currentX = currentX + colWidth For i = 1 To li.ListSubItems.Count Set subItem = li.ListSubItems(i) colWidth = MainList.ColumnHeaders(i + 1).Width ' 根据原逻辑设置子项背景色 If i >= FirstDate Then MainList.FillColor = RawMaterialShelf_Position_Settings_System.Offset(List_System, 0).Value Else MainList.FillColor = RawMaterialShelf_Position_Settings_System.Offset(List_Standard, 0).Value End If ' 绘制子项背景 MainList.FillRect currentX, rc.Top, currentX + colWidth, rc.Bottom ' 绘制子项文字 MainList.ForeColor = subItem.ForeColor MainList.DrawText subItem.Text, currentX, rc.Top, colWidth, rc.Bottom - rc.Top, dtLeft Or dtVerticalCenter currentX = currentX + colWidth Next i End Sub
注意事项
- 开启自绘后,ListView的默认渲染逻辑会被完全接管,选中状态、文字对齐等细节都需要手动实现。
- 确保
FirstDate、RawMaterialShelf_Position_Settings_System等变量在UserForm模块中可访问。
三、原代码修改建议
直接删除原代码中访问Li.ListSubItems(j + 1).BackColor的语句,根据需求选择上述两种方案替换:追求效率选方法1,需要精准控制子项选方法2。
内容的提问来源于stack exchange,提问作者Almesi
相关产品推荐
相关产品推荐

