How to convert a String to a Range Object

后端 未结 6 1529
名媛妹妹
名媛妹妹 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"))
    

提交回复
热议问题