我了解您对自定义函数表示保留,但老实说,这是我将采取的路线,而不是可能通过用户干预或代码执行意外操作/删除/等的隐藏列。
该子例程从 Cells(2,2) 获取字符串值,并通过下面的函数将其转换为 xlChartType。
Sub ChartTypes()
Dim cht As Chart
Dim ws As Worksheet
Dim stringType As String
Dim chartType As XlChartType
Set ws = Sheets(1)
stringType = CStr(Cells(2, 2).Value)
'Use the function to return the correct xlChartType in the AddChart:
Set cht = ws.Shapes.AddChart( _
GetChartTypeConstant(stringType), _
50, 50, 300, 200).Chart
End Sub
这是在Set cObj...
. 请注意,通过使用带有 case select 的函数,您可以使用更易于使用的名称,而不是“xlBarClustered”,您可以将其称为“Horizontal Bars”等。
Private Function GetChartTypeConstant(myString As String) As XlChartType
'This function returns an xlCharType constant value from a descriptive string
' which you will need to define or modify for your needs;
' using select case also means you can use more descriptive/user-friendly
' names on your worksheet.
Select Case myString
Case "xlBarClustered", "Clustered Bars", "Horizontal Bars"
GetChartTypeConstant = xlBarClustered
Case "xlColumnClustered", "Clustered Columns", "Vertical Columns"
GetChartTypeConstant = xlColumnClustered
Case "xlLine", "Lines Only"
GetChartTypeConstant = xlLine
'Additional cases can be added for
' additional chart types.
End Select
End Function
请注意,子或函数中没有错误处理。