Mik*_* D. 5 excel vba excel-vba excel-2010
我写了一些自动创建图表的VBA代码.此图表中的一个轴不使用普通标签,而是使用图形.我将图形存储为图像,然后使用.Copy和.Paste方法将此图像的副本存入图表.
这是令人困惑的地方.我需要旋转图像以使其与轴对齐(使用.rotation属性).但是当我设置.top和.left属性时,形状不会达到我期望的结果.事实上,将属性设置为0和0并不能达到我的预期.我已经尝试更改我在图像对象上设置属性的方式的顺序,但它只出现在不同的(错误的)位置.
我确定我错过了VBA/Excel如何放置对象相对于我设置顶部和左侧属性的一些重要方面.基本上我的目标是使图表左侧的图像具有与绘图区域高度相同的宽度(因为图像旋转我理论上这将使其大小相同).
此代码不起作用:
Sheets(ImageSheet).Shapes("agreement").Copy
c.Chart.Paste
c.Chart.Shapes(1).Rotation=270
c.Chart.Shapes(1).width = c.Chart.PlotArea.height
c.Chart.shapes(1).left = 5
c.Chart.Shapes(1).top = c.Chart.PlotArea.top
Run Code Online (Sandbox Code Playgroud)
我也试过这段代码
c.chart.Shapes(1).top = c.chart.PlotArea.top + c.Chart.PlotArea.height
Run Code Online (Sandbox Code Playgroud)
因为我想也许它正在计算"顶部"作为图像对象的左上角,当它没有旋转时(旋转270度使得这个点在它应该与绘图区域的底部对齐的地方).但这并没有达到我的预期.
图像是一个瘦的矩形,充当轴的标签.图表最终会像这样布局:http://imgur.com/NrSXR和轴标签图像就像这样http://imgur.com/08EWU
我在这里错过了什么?
我最终旋转并调整了图像大小,然后将其复制并粘贴到图表并定位。我必须使用 IncrementLeft 和 IncrementTop 方法,而不是直接设置 left 和 top 属性,因为这没有达到预期的效果。
当粘贴到图表中时,对象总是位于左上角,因此我可以向左增加我想要的少量作为我想要的边距,并将顶部增加 PlotArea.top 的值将其与绘图区域对齐。
我还感到惊讶的是,在创建图像副本时,它保留了我将其复制到新工作表和图表时所指的“名称”。一旦图像出现在图表上,这对于定位图像特别有用。
我还需要在程序的最后执行此代码,在其他所有内容都已定位和对齐之后,或者当我为其中一个系列定位数据标签时,它们将无法正确显示。
这是我最终使用的代码:
'make a copy of the label image and refer to it with a variable for convenience
Sheets(ImageSheet).Shapes("maturity").Copy
i = Sheets(ImageSheet).Shapes.Count
Sheets(ImageSheet).Paste
Dim axisImage As Shape
Set axisImage = Sheets(ImageSheet).Shapes(i + 1)
'rotate and resize the image
With axisImage
.Rotation = 270
.width = c.Chart.PlotArea.height
End With
'cut and paste the new image to the chart
axisImage.Cut
c.Chart.Paste
'position it in the chart using IncrementTop and IncrementLeft because setting the properties directly does not have the desired effect
c.Chart.Shapes("maturity").IncrementTop c.Chart.PlotArea.top
c.Chart.Shapes("maturity").IncrementLeft c.Chart.PlotArea.left - c.Chart.Shapes("maturity").height
Run Code Online (Sandbox Code Playgroud)