excel vba甘特图
时间: 2023-12-14 07:34:10 浏览: 390
VBA画甘特图.xlsm
5星 · 资源好评率100%
以下是使用Excel VBA绘制甘特图的步骤:
1. 打开Excel文件并按Alt + F11打开VBA编辑器。
2. 在VBA编辑器中,选择插入 -> 模块,然后在新模块中输入以下代码:
```VBA
Sub DrawGanttChart()
Dim StartDate As Date
Dim EndDate As Date
Dim Duration As Integer
Dim RowCount As Integer
Dim i As Integer
Dim j As Integer
Dim k As Integer
Dim ChartTitle As String
Dim ChartRange As Range
Dim Chart As ChartObject
Dim Series As Series
'设置甘特图标题
ChartTitle = "甘特图"
'设置甘特图数据范围
Set ChartRange = Range("A1:C10")
'获取数据行数
RowCount = ChartRange.Rows.Count
'创建图表对象
Set Chart = ActiveSheet.ChartObjects.Add(Left:=10, Width:=800, Top:=10, Height:=400)
'设置图表类型为甘特图
Chart.Chart.ChartType = xlGantt
'设置图表标题
Chart.Chart.HasTitle = True
Chart.Chart.ChartTitle.Text = ChartTitle
'设置X轴为日期格式
Chart.Chart.Axes(xlCategory).CategoryType = xlTimeScale
'设置Y轴标题
Chart.Chart.Axes(xlValue).HasTitle = True
Chart.Chart.Axes(xlValue).AxisTitle.Text = "任务"
'循环添加数据系列
For i = 2 To RowCount
StartDate = ChartRange.Cells(i, 2).Value
EndDate = ChartRange.Cells(i, 3).Value
Duration = EndDate - StartDate
Set Series = Chart.Chart.SeriesCollection.NewSeries
Series.Name = ChartRange.Cells(i, 1).Value
Series.Values = "{""" & Duration & """}"
Series.XValues = "{""" & StartDate & """}"
Next i
'设置数据系列格式
For j = 1 To Chart.Chart.SeriesCollection.Count
Chart.Chart.SeriesCollection(j).Format.Line.ForeColor.RGB = RGB(0, 0, 0)
Chart.Chart.SeriesCollection(j).Format.Line.Weight = 2
Chart.Chart.SeriesCollection(j).Format.Fill.ForeColor.RGB = RGB(255, 255, 255)
Next j
'设置甘特图样式
Chart.Chart.ApplyLayout (6)
'设置甘特图颜色
For k = 1 To Chart.Chart.SeriesCollection.Count
Chart.Chart.SeriesCollection(k).Interior.ColorIndex = k
Next k
End Sub
```
3. 在Excel中,输入甘特图数据并选择数据范围。
4. 按Alt + F8打开宏窗口,选择DrawGanttChart并运行它。
5. 甘特图将被绘制在Excel工作表上。
阅读全文