Results 1 to 13 of 13

How to implement this vb code in my excel doc?

Threaded View

Call How to implement this vb code... 11-25-2010, 04:00 PM
Call Re: How to implement this vb... 11-25-2010, 08:04 PM
Call Re: How to implement this vb... 11-26-2010, 08:16 PM
shg Re: How to implement this vb... 11-26-2010, 08:19 PM
Call Re: How to implement this vb... 11-26-2010, 08:48 PM
  1. #1
    Registered User
    Join Date
    11-08-2010
    Location
    London, England
    MS-Off Ver
    Excel 2003
    Posts
    25

    How to implement this vb code in my excel doc?

    Hi,

    I've found this code at http://www.vb-helper.com/howto_dista...t_to_line.html

    I'd like to know how I could use it.

    Can I reference it in a cell? If so how? Or is it a macro I can run? And how could I do that? (Do I select the cells I want to calculate?)

    I think it calculates the distance between a line segment (pointX1, pointY1 - pointX2, pointY2) and a point (X,Y) If I can reference it, how could I do that?

    Thanks for your reply

    ' Calculate the distance between the point and the segment.
    Private Function DistToSegment(ByVal px As Single, ByVal py _
        As Single, ByVal X1 As Single, ByVal Y1 As Single, _
        ByVal X2 As Single, ByVal Y2 As Single, ByRef near_x As _
        Single, ByRef near_y As Single) As Single
    Dim dx As Single
    Dim dy As Single
    Dim t As Single
    
        dx = X2 - X1
        dy = Y2 - Y1
        If dx = 0 And dy = 0 Then
            ' It's a point not a line segment.
            dx = px - X1
            dy = py - Y1
            near_x = X1
            near_y = Y1
            DistToSegment = Sqr(dx * dx + dy * dy)
            Exit Function
        End If
    
        ' Calculate the t that minimizes the distance.
        t = ((px - X1) * dx + (py - Y1) * dy) / (dx * dx + dy * _
            dy)
    
        ' See if this represents one of the segment's
        ' end points or a point in the middle.
        If t < 0 Then
            dx = px - X1
            dy = py - Y1
            near_x = X1
            near_y = Y1
        ElseIf t > 1 Then
            dx = px - X2
            dy = py - Y2
            near_x = X2
            near_y = Y2
        Else
            near_x = X1 + t * dx
            near_y = Y1 + t * dy
            dx = px - near_x
            dy = py - near_y
        End If
    
        DistToSegment = Sqr(dx * dx + dy * dy)
    End Function
    Last edited by Call; 11-28-2010 at 06:44 AM. Reason: Added Code Tags

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts

Search Engine Friendly URLs by vBSEO 3.6.0 RC 1