简体   繁体   English

复制粘贴图表Excel VBA

[英]Copy Pasting Charts Excel VBA

I am having a problem here with my VBA code. 我的VBA代码在这里有问题。

This is the first code I am writing in VBA. 这是我在VBA中编写的第一个代码。 Basically I want it to check a condition (Value of cell F7 in sheet2), and based on that I would like to paste one of two charts in sheet2. 基本上,我希望它检查条件(sheet2中单元格F7的值),并据此将其粘贴到sheet2中的两个图表之一。

    Private Sub CommandButton1_Click()


CommandButton1.Caption = "Stock Size Range"
CommandButton1.BackColor = 0
CommandButton1.ForeColor = 16777215

'Clear the chart area
 Charts("Chart41").ChartArea.Clear


If Sheets("sheet2").Range("F7") = 1 Then 'Aluminum Material


    Sheets("sheet3").ChartObjects("Chart666").Select
    Sheets("sheet3").ChartObjects("Chart666").Copy
    ChartObjects("Chart41").Paste

    Else

    Sheets("sheet4").ChartObjects("Chart888").Select
    Sheets("sheet4").ChartObjects("Chart888").Copy
    ChartObjects("Chart41").Paste

End If

End Sub

Thing is,, when I click on the command button, it gives me a Run-Time error "9": Subscript out of range and it points to the line ( Charts("Chart41").ChartArea.Clear) 问题是,当我单击命令按钮时,它给我一个运行时错误“ 9”:下标超出范围,它指向该行(Charts(“ Chart41”)。ChartArea.Clear)

Thank you, 谢谢,

(Sorry but I do not have enough reputation to write a comment and ask about more information, so I will do my best!) (对不起,但是我没有足够的声誉来发表评论并询问更多信息,所以我会尽力!)

Hello! 你好!

Maybe you need to go to the desired sheet where the chart will be pasted, create a chart and then associate an ID to it, for example "MyNewChart" (you change the chart ID in the "area" where is written "Node 5" in a red rectangle in this image http://i.stack.imgur.com/hf2Nq.png ) 也许您需要转到要粘贴图表的所需工作表,创建一个图表,然后将其关联一个ID,例如“ MyNewChart”(您可以在“区域”中更改图表ID,将其写为“节点5”。在此图片的红色矩形中http://i.stack.imgur.com/hf2Nq.png

Then in your code, when you need to paste the chart, you can write: 然后在代码中,当需要粘贴图表时,可以编写:

Sheets("WriteSheetNameHere").ChartObjects("MyNewChart").Paste

HTH ;) HTH;)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM