Is it possible to use VBA to change the range that users are allowed to edit?

I have a sheet with a list that is sortable by users when the sheet is protected, however they cannot change the values on the list. I did this by clicking on the button that says "Allow Users To Edit Ranges" then entering the range of the list that I want to them to be able to sort.

I want a code that will change that range based on some other criteria. I tried to record a macro of myself changing the range, but it just gave me an empty sub. Is there a way to do this? The code would hypothetically go like this:

Sub test()

'run my other code here

Dim lastrow As String
lastrow = Sheet7.Range("N1")

   UserRange = "$I1:$M" & lastrow

'run the rest of my code

End Sub
Any help on this, or suggestions on how to do this another way would be appreciated. I tried defining the range with a formula, but that only works once, as it converts the formula to a static range.

Thanks,
Chad