How can I convert a range to a string (VBA)?

后端 未结 8 446
故里飘歌
故里飘歌 2020-12-10 20:38

What is the best way to convert a range of cells to a string? I have a function that only takes a string as input so I need to convert the range to a string, while retaining

8条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-10 21:12

    To make a comma separated list of cell values in a range:

    Function RangeToString(ByVal myRange as Range) as String
        RangeToString = ""
        If Not myRange Is Nothing Then
            Dim myCell as Range
            For Each myCell in myRange
                RangeToString = RangeToString & "," & myCell.Value
            Next myCell
            'Remove extra comma
            RangeToString = Right(RangeToString, Len(RangeToString) - 1)
        End If
    End Function
    

    You could add extra functionality like inserting a semicolon instead of a comma if the row number increases.

    To use this function:

    Sub AnySubNameHere()
        Dim rng As Range
        Set rng = ActiveSheet.Range("A3:A10")
    
        Dim myString as String
        myString = RangeToString(rng)
    End Sub
    

提交回复
热议问题