Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Link cell with Excel Shape

Tags:

excel

shapes

vba

In excel, we insert a shape, and we can link it to a cells value, by selecting shape and typing the cell reference in formula bar. I want to know: How can we do that programmatically. Like

For Each shape As Excel.Shape In workshet.Shapes
  'is there something like shape.Formula or any method from which I can do the above
   task.         
Next

Here is what I want to do programmatically

It's been days now , I am searching it. Really Need help, Thanks Alot.

like image 843
Waqas Avatar asked Nov 18 '11 21:11

Waqas


1 Answers

You don't need to use Select to apply formulas to Shapes. Select should be avoided wherever possible as it bloats code, and can have unintended consequences - for example triggering Events

Instead you can work with the Formula directly by using DrawingOBject, seeFormAppwhich also will let you manipulate existing formula (ie add 6 cell to A2 to make it A8, A12 to A18 etc). The second code routine FormAdd makes this adjustment, it works on both cell addresses and range names

Sub FormApp()
    Dim Shp As Shape
    For Each Shp In ActiveSheet.Shapes
        'formula
         Shp.DrawingObject.Formula = "=A1"
        'range name
        Shp.DrawingObject.Formula = "=RangeName"
    Next
End Sub

Sub FormAdd()
    Dim Shp As Shape
    Dim rng1 As Range
    For Each Shp In ActiveSheet.Shapes
        Set rng1 = Nothing
        If Len(Shp.DrawingObject.Formula) > 0 Then
            On Error Resume Next
            Set rng1 = Range(Shp.DrawingObject.Formula)
            On Error GoTo 0
            If Not rng1 Is Nothing Then Shp.DrawingObject.Formula = "=" & rng1.Offset(6, 0).Address
        End If
    Next
End Sub
like image 91
brettdj Avatar answered Sep 23 '22 22:09

brettdj