2013-04-16 234 views
3

我想在特定单元格位置添加形状,但由于某些原因无法获得在所需位置添加的形状。下面是我使用添加形状代码:vba在Excel中的特定单元格位置添加形状

Cells(milestonerow, enddatecellmatch.Column).Activate 

Dim cellleft As Single 
Dim celltop As Single 
Dim cellwidth As Single 
Dim cellheight As Single 

cellleft = Selection.Left 
celltop = Selection.Top 

ActiveSheet.Shapes.AddShape(msoShapeOval, cellleft, celltop, 4, 10).Select 

我使用的变量捕捉左侧和顶部位置,检查与值我添加形状,当看到正在在我的代码设置的值在录制宏时在手动位置手动。当我运行我的代码时,cellleft = 414.75和celltop = 51,但是当我在录制宏时手动添加形状到活动单元位置时,cellleft = 318.75和celltop = 38.25。我一直在解决这个问题,并且在线查看了很多关于添加形状的现有问题,但我无法弄清楚。任何帮助将不胜感激。

+0

上述代码对我来说绝对合适。 –

+0

'。激活'在第一行不一定意味着它等于选择然后...你需要检查它。或者在第一行中简单地将'.Activate'改成'.Select'。 –

+1

我有同样的问题。 .Cell.Left和形状的真实位置之间有一点区别。 这个“bug”只发生在excel 2007上。在excel 2003中,vba代码运行良好。在2010年,我不知道。 我尝试Debug.Print,但我看不到任何效果。 – 2013-09-04 14:30:43

回答

6

这似乎是为我工作。我在最后添加了调试语句以显示形状的.Top.Left是否等于单元的.Top.Left值。

为此,我选择了单元格C2

Shape inserted at cell's top & left

Sub addshapetocell() 

Dim clLeft As Double 
Dim clTop As Double 
Dim clWidth As Double 
Dim clHeight As Double 

Dim cl As Range 
Dim shpOval As Shape 

Set cl = Range(Selection.Address) '<-- Range("C2") 

clLeft = cl.Left 
clTop = cl.Top 
clHeight = cl.Height 
clWidth = cl.Width 

Set shpOval = ActiveSheet.Shapes.AddShape(msoShapeOval, clLeft, clTop, 4, 10) 

Debug.Print shpOval .Left = clLeft 
Debug.Print shpOval .Top = clTop 

End Sub 
+0

我在你的调试部分中添加了图形和单元格左和顶点都是相同的,所以我不知道它为什么不起作用。我保存了工作簿,关闭了Excel,然后重新打开,然后工作正常,所以不确定是什么问题,但感谢您的回答。 – Casey

0

我发现这个问题是由只有当缩放级别不是100%会发生的错误引起的。在这种情况下,单元格位置通知不正确。

解决方法是将缩放比例更改为100%,设置位置,然后更改回原始缩放比例。您可以使用Application.ScreenUpdatinf来防止闪烁。

Dim oldZoom As Integer 
oldZoom = Wn.Zoom 
Application.ScreenUpdating = False 
Wn.Zoom = 100 'Set zoom at 100% to avoid positioning errors 

    cellleft = Selection.Left 
    celltop = Selection.Top 
    ActiveSheet.Shapes.AddShape(msoShapeOval, cellleft, celltop, 4, 10).Select 

Wn.Zoom = oldZoom 'Restore previous zoom 
Application.ScreenUpdating = True 
相关问题