How to convert a String to a Range Object

后端 未结 6 1504
名媛妹妹
名媛妹妹 2021-01-23 22:44

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

相关标签:
6条回答
  • 2021-01-23 23:09

    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"))
    
    0 讨论(0)
  • 2021-01-23 23:15

    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
    
    0 讨论(0)
  • 2021-01-23 23:18

    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
    
    0 讨论(0)
  • 2021-01-23 23:20

    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 讨论(0)
  • 2021-01-23 23:24

    A string with a cell address? if so:

    Dim r As Range: Set r = Range("B3")
    MsgBox r.ColumnWidth
    
    0 讨论(0)
  • 2021-01-23 23:26

    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 ?

    0 讨论(0)
提交回复
热议问题