我试图写一些VBA来检查以确保图表具有特定标题。这就是我现在所拥有的。
Sub check_chart_title()
Worksheets(1).ChartObjects(3).Activate
With ActiveWorkbook.ActiveChart
.HasTitle = True
.ChartTitle.Select
End With
If Selection = "Sales" Then 'code crashes here
x = "good" 'proceed to the rest of the code, no chart title mismatch
Else: x = "bad" 'specific action to take if there is a chart title mismatch
End If
End Sub
我知道问题在于if语句的条件。但我还没有找到办法在图表标题上运行条件。我只需要能够识别图表标题是否等于某个字符串的代码。
非常感谢任何帮助。
答案 0 :(得分:3)
而不是选择图表标题然后测试它,只需将它放在IF
语句中。
With ActiveWorkbook.ActiveChart
.HasTitle = True
.ChartTitle.Select
If .ChartTitle.Text = "Sales" Then 'code crashes here
x = "good" 'proceed to the rest of the code, no chart title mismatch
Else
x = "bad" 'specific action to take if there is a chart title mismatch
End If
End With
答案 1 :(得分:2)
可能是你这样的事情:
Sub check_chart_title()
Worksheets(1).ChartObjects(3).Activate
With ActiveChart
.HasTitle = True
.ChartTitle.Select
If .name = "Sales" Then
x = "good" 'proceed to the rest of the code, no chart title mismatch
Else
x = "bad" 'specific action to take if there is a chart title mismatch
End If
End With
End Sub
答案 2 :(得分:1)
如果要合并with
:
Dim myChart As Chartobject
set myChart = Sheets(1).ChartObjects(3)
With myChart
if .ChartTitle.Text = "Sales" then
x = "Good"
Else
x = "Bad"
end if
'Do some other stuff
end with
'