【问题标题】:Using Inputbox Value to Create Chart Title in VBA在 VBA 中使用输入框值创建图表标题
【发布时间】:2016-09-30 03:43:40
【问题描述】:

问题:

您需要创建三个变量,如下所示:

“rangeData”:存储当前选中的范围。 "titleChart": 存储图表标题 "nameSheet" : 存放工作表名

您将使用InputBox 函数两次来获取图表的标题和工作表的名称,并使用为图表指定的标题和为工作表指定的名称。

到目前为止,我一直坚持将值从 InputBox 获取到新图表标题:

到目前为止我的代码:

Dim RangeData As Integer
Dim rng As Range

Dim ctInputbox As String
Dim CT As ChartTitle

Dim nsnInputbox As String
Dim nsn As Worksheet

'Change Data source to currentley selected cells
Set rng = Selection

'Add a chart onto the active sheet and select the chart
ActiveSheet.Shapes.AddChart.Select

'Chart type is Clustered Column chart
ActiveChart.ChartType = xlColumnClustered

'Assign a chart title:

'instead of using the content of cell H13 as the chart title, ask
'the user for the title of the chart and set the title

'Add user data to create a chart title    
ctInputbox = InputBox("Please enter a chart title", "Chart Title Name")
ActiveChart.HasTitle = True

With ActiveChart.ChartObjects
    Set CT = ctInputbox
End With

End Sub

【问题讨论】:

    标签: vba excel macros inputbox


    【解决方案1】:

    Set CT = ... 在右侧需要一个ChartTitle 对象,而InputBox() 函数返回一个String

    此外ActiveChart.ChartObjects “返回一个对象,该对象表示工作表上的单个嵌入图表(ChartObject 对象)或所有嵌入图表(ChartObjects 对象)的集合。” em>,其中不是你要设置的图表标题...

    相反,您想设置使用相关Chart 对象的ChartTitle 属性检索到的ChartTitle 对象的Text 属性。

    我更喜欢Application.InputBox() 方法而不是VBA InputBox() 函数,因为前者允许您通过其Type 参数强制用户输入类型: 将其设置为2 将强制输入字符串。

    最后,在将 Selection 分配给 Range 对象之前,始终检查前者是否真的 Range 对象

    所以这里有什么你可以去的:

    'Change Data source to currentley selected cells
    If TypeName(Selection) <> "Range" Then Exit Sub '<--| exit if selection is not a 'Range (i.e. it might be a 'Chart')
    Set rng = Selection '<--| now you can do that safely
    
    'Add a chart onto the active sheet and select the chart
    ActiveSheet.Shapes.AddChart.Select
    
    With ActiveChart
        'Chart type is Clustered Column chart
        .ChartType = xlColumnClustered
    
        'Add user data to create a chart title
        .HasTitle = True
        .ChartTitle.Text = Application.InputBox("Please enter a chart title", "Chart Title Name", Type:=2)
    End With
    

    【讨论】:

      【解决方案2】:

      用你的object.chart

        .SetElement  msoElementChartTitleAboveChart 
      
        .ChartTitle.Caption = Title$
      

      结束

      【讨论】:

        猜你喜欢
        • 2010-11-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-10-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多