在MS Project VBA中如何遍历所有甘特图条形图样式?
MS Project VBA 甘特图条形图样式的遍历与管理
MS Project VBA没有提供类似Tasks集合那样可直接遍历的甘特图条形图样式对象/集合,所有相关操作只能通过Application对象下的一系列方法(如GanttBarStyleDelete、GanttBarStyleEdit、GanttBarStyleExists)间接完成。
优化删除所有甘特图条形图样式的方法
你当前的循环删除方法可行但不够灵活,硬写循环次数缺乏通用性。可以通过判断样式是否存在来循环删除,直到清空所有样式:
Sub DeleteAllGanttBarStyles() Dim styleIndex As Integer styleIndex = 1 Do While True ' 检查当前索引的样式是否存在 If Not Application.GanttBarStyleExists(styleIndex) Then Exit Do End If ' 删除该索引的样式(删除后后续样式自动前移,无需递增索引) Application.GanttBarStyleDelete(styleIndex) Loop End Sub
获取单个甘特图条形图样式的信息
虽然没有直接的样式对象,但可以借助GanttBarStyleEdit方法结合错误捕获,读取现有样式的名称、格式等属性。例如读取所有样式的名称:
Sub ListGanttBarStyleNames() Dim styleIndex As Integer Dim styleName As String styleIndex = 1 Do While True On Error Resume Next ' 传入空字符串参数,返回当前索引样式的名称 styleName = Application.GanttBarStyleEdit(styleIndex, Name:="") ' 出错则说明无对应索引的样式,退出循环 If Err.Number <> 0 Then On Error GoTo 0 Exit Do End If On Error GoTo 0 Debug.Print "样式索引:" & styleIndex & ",名称:" & styleName styleIndex = styleIndex + 1 Loop End Sub
补充说明
GanttBarStyleEdit方法的参数具备读写双重作用:传入空值时返回当前属性值,传入具体值则修改属性。利用这个特性可以读取条形图的形状、颜色、文本位置等其他属性。- 操作时需注意:甘特图的默认样式(如“任务”“摘要任务”)无法被彻底删除,删除后会自动恢复基础样式,这是MS Project的内置限制。
内容的提问来源于stack exchange,提问作者Stgauss
相关产品推荐
相关产品推荐

