UDF for a non-UDF vba

mrc44

Board Regular
Joined
Aug 12, 2017
Messages
64
Is it possible to make the vba code below a UDF function? Instead of running macro with F8 everytime, I'd like to use it with a UDF function only for specific cells? Thanks!

Code:
Sub Intervals()    Dim r As range, C As range
    With Cells(1).CurrentRegion
        With .Offset(1).Resize(.Rows.Count - 1)
            For Each r In .Cells
                Set C = .Find(r.Value, r, , 1, , , 2)
                If (C.Address <> r.Address) * (C.Row > r.Row) Then
                    r.Offset(, 6) = C.Row - r.Row - 1
                Else
                    r.Offset(, 6) = "na"
                End If
            Next
        End With
    End With
End Sub
 
Last edited:

Excel Facts

Bring active cell back into view
Start at A1 and select to A9999 while writing a formula, you can't see A1 anymore. Press Ctrl+Backspace to bring active cell into view.
No, simply because a UDF can only write into a single cell, your sub appears to write into lots of cells.
 
Upvote 0
Thanks, offhelip. so is it possible to make it work on a range of cells instead of the whole data?
 
Upvote 0
yes very easily just change the code as below ( I put in the range A1 to G23 just as an example)

Code:
Sub Intervals()
Dim r As Range, C As Range
    With Range("A1:G23")
            For Each r In .Cells
                Set C = .Find(r.Value, r, , 1, , , 2)
                If (C.Address <> r.Address) * (C.Row > r.Row) Then
                    r.Offset(, 6) = C.Row - r.Row - 1
                Else
                    r.Offset(, 6) = "na"
                End If
            Next
        End With
End Sub
 
Upvote 0

Forum statistics

Threads
1,223,911
Messages
6,175,327
Members
452,635
Latest member
laura12345

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top