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

Format cells as date
Select range and press Ctrl+Shift+3 to format cells as date. (Shift 3 is the # sign which sort of looks like a small calendar).
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,216,116
Messages
6,128,932
Members
449,480
Latest member
yesitisasport

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