开发者

How to convert a String to a Range Object

开发者 https://www.devze.com 2023-01-01 06:12 出处:网络
Is there anyway to convert a string value to a Range object ? I\'m having a function which takes a Range object as a argument and need to pass a single string parameter to it

Is there anyway to convert a string value to a Range object ? I'm having a function which takes a Range object as a argument and need to pass a single string parameter to it

开发者_运维技巧

Thank You


A string with a cell address? if so:

Dim r As Range: Set r = Range("B3")
MsgBox r.ColumnWidth


I don't like this one bit, but if you can't change the function that requires a range, you could create a function that converts a string to a range. You'd want to be sure that the only thing the first function cares about is the Value or Text properties.

Function FuncThatTakesRange(rng As Range)

    FuncThatTakesRange = rng.Value

End Function

Function ConvertStringToRange(sInput As String) As Range

    Dim ws As Worksheet

    Set ws = Workbooks.Add.Sheets(1)

    ws.Range("A1").Value = sInput

    Set ConvertStringToRange = ws.Range("A1")

    Application.OnTime Now + TimeSerial(0, 0, 1), "'CloseWB """ & ws.Parent.Name & """'"

End Function

Sub CloseWb(sWb As String)

    On Error Resume Next
        Workbooks(sWb).Close False

End Sub

Use in the Immediate Window like

?functhattakesrange(convertstringtorange("Myvalue"))


Here is my solution that involves no need for a new function.

1.Make dynamic string variable first

2.Then finalize it by creating a range object out of this string via a range method: Set dynamicrange= range (dynamicstring)

You can manipulate dynamicstring as you want to, I just kept it simple so that you can see that you can make range out of a string variable.


Sub test()

Dim dynamicrangecopystring As String
Dim dynamicrangecopy As range
dynamicrangecopystring = "B12:Q12"
Set dynamicrangecopy = range(dynamicrangecopystring)

End Sub


Why not change the function argument to a variant and then in the function determine Using VarType etc) if you have been passed a Range and use error handling to check for a string which can be converted to a range or a string that cannot be converted to a range ?


This simple function will convert string arguments into a range object, usable in other excel functions.

Function TXT2RNG(text) As Variant

Set TXT2RNG = Range(text)

End Function


Let's say Sheet1!A1 has the text value "Sheet1!B1" and Sheet1!B1 has the value "1234". The following code will use the range address stored as text in A1 as an input and copy the range B1 to A2:

Sub Tester()

  Sheet1.Range(Range("A1")).Copy

  Sheet1.Range("A2").PasteSpecial xlPasteAll

End Sub
0

精彩评论

暂无评论...
验证码 换一张
取 消