excel,vba,excel-vba , Excel 2013 Add a Connector Between Arbitrary Points on Two Different Groups


Excel 2013 Add a Connector Between Arbitrary Points on Two Different Groups

Question:

Tag: excel,vba,excel-vba

I'm working in Excel 2013 to (programmatically) add a straight line connector between the lower right hand corner of a rectangle that is part of a grouped shape with the endpoint of a grouped series of line segments. As it stands, I can't even seem to do this manually on the Excel worksheet that contains these shapes.

Problems include:

  1. Only midpoints on the desired rectangle will accept the connector.
  2. The grouped series of line segments don't even show a "connection point" for the terminating end of the straight line connector.

Here's a graphic of what I'm trying to do:

[I don't have 10 "reputation points" so I can't seem to post a picture of what I'm trying to do. Not an especially helpful feature! How do I get reputation points in this game?]

I've been able to create and name the two groups and thought it would be a cinch to work with them to add a connector, but that has not been the case.

Here's the code I've been working with:

Sub create_new_profile()
    Dim firstRect As Shape
    Dim firstLine As Shape
    Set myDocument = Worksheets(1)
    Set s = myDocument.Shapes
'    Set firstRect = s.Range("shpNewGarage")
'    Set firstLine = s.Range("shpProfile")
    Dim Shp As Shape
'    For Each Shp In myDocument.Shapes
    For Each Shp In s
        If Shp.Name = "shpNewGarage" Then
            Set firstRect = Shp
    Else
    End If
    Next Shp
'    For Each Shp In myDocument.Shapes
    For Each Shp In s
        If Shp.Name = "shpProfile" Then
            Set firstLine = Shp
    Else
    End If
    Next Shp
    firstRect.Select 'this works
    firstLine.Select 'this works
'    Set firstRect = s.AddShape(msoShapeRectangle, 100, 50, 200, 100)
'    Set firstLine = s.AddShape(msoShapeRectangle, 300, 300, 200, 100)
'    Set firstRect = ActiveSheet.Shapes.Range("shpNewGarage")
'    Set firstLine = ActiveSheet.Shapes.Range("shpProfile")
    Dim c As Shape
    Set c = s.AddConnector(msoConnectorStraight, 0, 0, 100, 100)
'    On Error Resume Next
    With c.ConnectorFormat
      **.BeginConnect ConnectedShape:=firstRect, ConnectionSite:=1**
      .EndConnect ConnectedShape:=firstLine, ConnectionSite:=1
'     .BeginConnect ConnectedShape:="shpNewGarage", ConnectionSite:=1
'     .EndConnect ConnectedShape:="shpProfile", ConnectionSite:=1
'     .BeginConnect ConnectedShape:=ActiveSheet.Shapes.Range("shpNewGarage"), ConnectionSite:=1
'     .EndConnect ConnectedShape:=ActiveSheet.Shapes.Range("shpProfile"), ConnectionSite:=1
     c.RerouteConnections
    End With
End Sub

This particular version of the code ends with a runtime error on the line immediately following the line:

With c.ConnectorFormat

Here's the error message:

[I don't have 10 "reputation points" so I can't seem to post a picture of the error message I'm getting. Again, how do I get reputation points?]

Any direction at all to help me accomplish this task programmatically would be greatly appreciated.

Thanks for explaining that I can now post images. That should help.

Here are the figures I'm working with:

New garage, existing driveway profile and new profile (red.)

The rectangle group (firstRect, "shpNewGarage") represents a new garage I plan to build between the existing one and the street. The profile group (firstLine, "shpProfile") represents the profile (side view/elevation) of the existing driveway (the light blue line.) The idea is to attach the new profile (red line) to the lower right corner of the new garage at one end and to the right end of the existing profile (curb) so that as I move the new garage up, down, right and left, the connector representing the new profile will remain attached to these points to show graphically the angle (grade) and length of the new driveway.

Here's the error message I receive when I run the code:

VBA error message.

This looks like quite a hill to climb, as I am having problems even adding the connector to the desired points manually.

Thanks to all who have read/responded to my issue. Stackoverflow has been a great resource to me in the past, and this is the first time I've ever had to post my own fairly specific problem.


Answer:

You explained everything very well, and the images you uploaded helped

What your code is doing seems to be correct, but the error is complaining about one of the parameters, and it could be the 2nd one:

.BeginConnect ConnectedShape:=firstRect, ConnectionSite:=1

ConnectionSite: "A connection site on the shape specified by ConnectedShape. Must be an integer between 1 and the integer returned by the ConnectionSiteCount property of the specified shape"

I think your firstRect has a problem with the first Node: when you initially generate a rectangle it doesn't have connection points in the corners, and I'm not sure about the initial available nodes

A rectangle is a specific class of shape that must first be converted to a (generic) shape class: "You must apply the AddNodes method to a FreeformBuilder object at least once before you use the ConvertToShape method", in order to add connection points (nodes) to the corner

Another issue might be caused by groups. I'm not sure if you grouped the objects, but grouping may not allow direct access to connection points

As an exercise, I was able to draw lines between 2 rectangles the way you intended, but my lines are not actually connected to the shapes, so if I move one rectangle the lines will not move with it. Here is my code:

Option Explicit

Sub create_new_profile()

    Dim ws As Worksheet

    Dim shp1 As Shape
    Dim shp2 As Shape

    Dim line1 As Shape
    Dim line2 As Shape

    Set ws = Sheet1

    With ws.Shapes

        'AddShape:        Left=10, Top=10, Width=50, Height=30
        Set shp1 = .AddShape(msoShapeRectangle, 10, 10, 50, 30)
        Set shp2 = .AddShape(msoShapeRectangle, 70, 50, 50, 30)

        'AddConnector:          BeginX=60, BeginY=10, EndX=120, EndY=50
        Set line1 = .AddConnector(msoConnectorStraight, 60, 10, 120, 50)
        Set line2 = .AddConnector(msoConnectorStraight, 60, 40, 120, 80)
    End With

    line1.Line.ForeColor.RGB = RGB(255, 0, 0)   'Color Red
    line2.Line.ForeColor.RGB = RGB(255, 0, 0)

End Sub

and this is the end result:

connected shapes

.

If you need the lines to be linked to the rectangles, you'll have to convert the rectangles to shapes, then add corner connection points or nodes (msoEditingCorner), then add connector lines from one corner node of the first rectangle to the other corner node of the second rectangle

One of the ways to (manually) convert to shape, and record your actions to see the generated VBA code and objects used, is by right-clicking the shape and selecting "Edit Points":

enter image description here

Hope this helps a bit


Related:


NoClassDefFoundError: UnsupportedFileFormatException while using apache poi to write to an excel file


java,excel,apache-poi,writing
I am trying to write to an excel(.xlsx) file using Apache poi, I included the apache poi dependencies in my pom.xml file. But I am getting the following exception in execution. Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/poi/UnsupportedFileFormatException at java.lang.ClassLoader.defineClass1(Native Method) at java.lang.ClassLoader.defineClass(ClassLoader.java:800) at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142) at java.net.URLClassLoader.defineClass(URLClassLoader.java:449) at...

VBA “Compile Error: Statement invalid outside Type Block”


excel,vba,excel-vba,excel-2010
I am running a VBA Macro in Excel 2010 with tons of calculations, so data types are very important, to keep macro execution time as low as possible. My optimization idea is to let the user pick what data type all numbers will be declared as (while pointing out the...

Using a stored integer as a cell reference


excel,excel-vba,reference
Dim x As Integer Dim y As Integer For y = 3 To 3 For x = 600 To 1 Step -1 If Cells(x, y).Value = "CD COUNT" Then Cells(x, y).EntireRow.Select Selection.EntireRow.Hidden = True End if If Cells(x, y).Value = "CD Sector Average" Then Cells(x, y).EntireRow.Select Selection.Insert Shift:=xlDown Cells(x +...

Copying sheet to last row of a sheet from another workbook


excel,vba,excel-vba
I'm stuck in this block of code that copies sheet("Newly Distributed") to the last row of sheet("Source") from another workbook. The error is runtime error 9. What's wrong with my code? Any response would be appreciated. Private Sub copylog3() Dim lRow As Long Dim NextRow As Long, a As Long...

VBA how to initialize vCPath


vba,excel-vba,excel-2010
How do I initialize vCPath? VBA Run-Time Error 1004 @Garry's Student says I "must somehow use the info you get from Application.FileDialog(msoFileDialogOpen) to generate the full filespec of the file you wish to open". What's the simplest way to do this? I am a VBA beginner: I have been programming...

12 Characters Including leading and following zeros


excel
I am finding this difficult to explain, but ultimately I am wanting a cells value to be 12 characters long including +/- a decimal point and following zeroes. Examples are 1200 would become +1200.000000 -20 would become -20.00000000 99999999 would become +99999999.00 I have tried FIXED, LENGTH, and formatting rules...

Copying a Range from Excel and Pasting it into Powerpoint NOT as a metafile but as a table which you can edit in PPP


vba,excel-vba,powerpoint-vba
All I want to do is copy a range from Excel and then paste this range into PowerPoint. When my range is manually copied from Excel to the clipboard... If I right click on a blank slide when pasting into PowerPoint, it gives me the option to paste "using destination...

Creating a Range in VBA


vba,range
I'm working on my first VBA function. The goal is to have a function that accepts two integers as inputs, and outputs an array containing all the integers in between the two inputs (end-points included). Example: If I input 5 and 9, the output should be an array of 5,...

I need help setting the RecordSource of a Report within a VBA Function


vba,ms-access,access-vba
Ok, so I've been looking around here for a few days (and a few other sites) and while I have modified my code a good bit to find a solution, it still doesn't work. I have four source queries, and I'd like to set the record source of my report...

adding variables into another variable vba


excel,vba,excel-vba
Dim x As Long Dim y As Long Dim CDTotal As Double Dim CSTotal As Double Dim ETotal As Double Dim FTotal As Double Dim HTotal As Double Dim ITotal As Double Dim ITTotal As Double Dim MTotal As Double Dim TTotal As Double Dim UTotal As Double Dim TotalValue...

Excel-VBA: create named Range in row until end of cell content


vba,excel-vba,range
Imagine an Excel sheet with some rows and some content in each row (i.e. different column-length for each row). In Excel-VBA: How can I create a range-X within column-X that goes from row-cell-2 to the end of the content of this X-column ?? i.e. I would like to create a...

How do you delete favorite folders in outlook using VBA


vba,outlook-2007
I wish to delete all the folders from the outlook favorites then subsequently replace them, but the delete doesn't seem to work. What's wrong with my code. Setup Objects works fine ' Get the "Favorite Folders" navigation group Set favGroup = Application.ActiveExplorer.NavigationPane.Modules.GetNavigationModule(olModuleMail).NavigationGroups.GetDefaultNavigationGroup(olFavoriteFoldersGroup) This works Set inboxFldr = Application.GetNamespace("MAPI").GetDefaultFolder(olFolderInbox) favGroup.NavigationFolders.Add (inboxFldr)...

Using date in CreateQueryDef


vba,date,ms-access
I have a table on which I run a query that I export to Excel. Here is an example: Table: Food Item | Price | Limit_Date | ------------------------------- Carrot | 0.80 | 08/07/2015 | Salmon | 4.30 | 01/07/2015 | Biscuits | 2.40 | 15/12/2015 | Milk | 1.00 |...

Excel VBA Program Code by Using Randomize Timer


vba
What is wrong in below program code, why not returning correct result. Whenever i put any number in excel cell (1,1) and run the program, Numbers changed automatically, also not throwing a correct result in cell (1,2). Please Help as i learning VBA. Private Sub Sheet2_1() Dim num1 As Integer...

If cell value starts with a specific set of numbers, replace data


excel,vba,excel-vba
My cell values are strings of numbers (always greater than 5 numbers in a cell, ie 67391853214, etc.) If a cell starts with three specific numbers (ie 673 in a cell value 67391853214) I want the data in the cell to be replaced with a different value (if 673 are...

Which is faster in Excel, an if formula giving 1 or 0 instead of true/false or --?


excel
I've got a large spreadsheet that I'm trying to optimise as it has over 12,000 lines of data, with in excess of 28 columns. It currently takes a significant amount of time to execute and I'm therefore starting to pare it down. As part of this I've started looking at...

Converting ADODB Loop into DAO


excel,vba,ms-access,ado,dao
Hi I've been developing a vba project with a lot of help from examples here. I'm trying to access a MS Access database from Excel VBA and import large data sets (500-100+ rows) per request. Currently, the following loop works using ADODB however, the Range("").Copyfromrecordset line is taking very long...

Using VLOOKUP formula or other function to compare two columns


mysql,excel,vba,date
I have one table like this: SHORT TERM BORROWING 1/6/2009 94304 12/31/2010 177823 6/30/2011 84188 12/31/2011 232144 6/30/2012 94467 9/30/2012 91445 12/31/2012 128523 3/31/2013 83731 6/30/2013 78330 9/30/2013 70936 12/31/2013 104020 3/31/2014 62345 6/30/2014 62167 9/30/2014 63494 12/31/2014 104239 3/31/2015 69056 I have another column which lists each date from...

VBA - Unable to pass value from Private to Public Sub


excel,vba,excel-vba
I have a tool which I am designing to present a number of questions to a user in a set of userforms. The form will generate a score via passing an integer result from the userform to a main sub, which passes the code to a worksheet. My problem is...

Removing Alert When Using DeleteFile API


vb.net,vba,api,delete
I'm writing a VBA application which involves looping a large number of directories recursively. I am using the FindFirstFile API to to achieve this, as it offers a substantial performance boost over the FileSystemObject. In order to remove the FSO from my code entirely, I need a routine to delete...

Activecell not in Array


vba
Having difficulty comparing my activecell against a predefined array. After importing data from another source I want to trim out the columns I don't need I've trued the array as both undefined, string and variant And tried activecell / activecell.value <> NeededColumns No joy :( Sub Trim() Dim NeededColumns As...

How to insert excel formula to cell in Report Builder 3.0


sql-server,excel,reporting-services,excel-formula,ssrs-2008-r2
There is RDL report template for SQL Server Reporting Services. I need to set value for cell in table in the report template which must be calculated from other values in the report. When the report is exported to Excel file I need to see the Excel formula in that...

Excel VBA Loop Delete row does not start with something


excel,excel-vba
I have some data at work looks like this: 00 some data here... 00 some data here... 00 some data here... 00 some data here... Other data I want to remove Other data I want to remove Other data I want to remove Other data I want to remove 00I...

Userform is not unloading once command button is pressed


vba,excel-vba
Having a little trouble with my userform, its not unloading once i hit the command button the data is inputted to the sheet but the userform is not refreshed and the data stays in the text boxes. It was working fine until i put the data validation in, but i...

VBA data type to store Range().Characters()


vba
I can't find a data type to store Characters from a Range. I already tried the following code, but nothing happened. I think the problem is because of wrong data type. Dim chars As Characters chars = Range("A2").Characters(0, 4) MsgBox chars.Text ...

Interface Controls for DoEvent in Excel


excel,vba,excel-vba,loops,doevents
I have a macro to loop through a range and return emails to .Display based on the DoEvents element within my module. I iterate that: row_number = 1 'And Do DoEvents row_number = row_number +1 'Then a bunch of formatting requirements Loop Until row_number = 'some value I am wondering...

Excel - select a cell based on adjacent cell value


excel
I have the following excel spreadsheet and I am trying to work out how I can write a formula in order to provide the values in column D. In each row, there is a test date, I am trying to calculate the day difference from each test date to the...

excel search engine using vba and filters?


excel,vba
I am using the following vba code to filter my rows in excel based on the value in my cell C5 Sub DateFilter() 'hide dialogs Application.ScreenUpdating = False 'filter for records that have June 11, 2012 in column 3 ActiveSheet.Range("C10:AS30").AutoFilter Field:=1, Criteria1:="*" & ActiveSheet.Range("C5").Value & "*" Application.ScreenUpdating = True End...

Exit Sub And Call another Sub


vba,excel-vba,call
I have two subs, sub1 and sub2. I want to exit sub1 completely and start sub2 if a condition is satisfied. My attempt is (running from : sub1 . . If x=y Then Exit Sub And Call sub2 End If . . End Sub ...

timestamp SQL to Excel


php,mysql,sql,excel
If this is a duplicate, please let me know, I haven't found anything. I have written a php file that can read content from a database table and write it into a excel .xls file. Everything works fine except by that timestamps. In my generated .xls file every timestamp is...

EXCEL VBA: How to manupulate next cell's (same row) value if cell.value=“WORD” in a range


excel,vba,excel-vba
I want to change the next cell in same row in a if cell.value="word" in a range. I have defined the range, using 'for' loop. In my code, if cell.value="FOUND THE CELL" then cell.value+1="changed the next right side cell" cell.value+2="changed the second right side cell" end if I know this...

Excel - Pulling data from one cell within a list


excel,powerpoint,spreadsheet
I use PowerPoint as a graphics template to type up football player names and there squad numbers. It can be a long procedure and so far following YouTube tutorials i have managed to create a form in Excel which can update the text boxes in PowerPoint at the click of...

Comparing cell contents against string in Excel


string,excel,if-statement,comparison
Following is my table file:*.css file:*.csS file:*.PDF file:*.PDF file:*.ppt file:*.xls file:*.xls file:*.doc file:*.doc file:*.CFM file:*.dot file:*.cfc file:*.CFM file:*.CFC file:*.cfc file:*.DOC I need a formula to populate the H column with True or False if it finds column G in column F (exact case). I used following but nothing seems to...

Identifying cell in Openpyxl


python,excel,openpyxl
I've been working on a project, in which I search an .xlsx document for a cell containing a specific value "x". I've managed to get so far, but I can't extract the location of said cell. This is the code I have come up with: from openpyxl import load_workbook wb...

Extract All Named Ranges Into A Class


vba,excel-vba
I have a workbook with a very large amount of named ranges (well over 200). I really need a way to work quickly and easily with all of the named ranges so I can then work with / populate them using VBA. My solution up until now has been to...

Converting column from military time to standard time


r,excel
I'm trying to convert a column showing the time of road traffic accidents from military time to standard time. The data looks like this: Col1 Time..24hr. 1 1404 2 322 3 1945 4 1005 5 945 I'd then like to convert to 12hr so for '322' I'd like to make...

Using a cell's number to insert that many rows (with that row's data)


excel,excel-vba
I have data in excel that looks like this {name} {price} {quantity} joe // 4.99 // 1 lisa // 2.99 // 3 jose // 6.99 // 1 Would it be hard to make a macro that will take the quantity value ("lisa // 3.99 // 3") and add that many...

How do I do to count rows in a sheets with filters? With a suppress lines


excel,vba,filter
I have a sheet with lots of columns, but when I filter and use count = Application.WorksheetFunction.CountA(Range("A:A")) It returns all the rows non Empty. Not only the rows I filtered....

Replace reference with its value in Excel VBA workbook


vba,excel-vba
I have an Excel workbook to manage my Delivery Notes, which creates another workbook with actual delivery note and stores it in the folder for me, then places new record in my main workbook so that the Delivery Number for the next delivery note can be increased by 1. My...