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

后端 未结 8 436
故里飘歌
故里飘歌 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:22

    There is a much easier way. Assuming the variable rng is a range, then writing:

    rng = Left(rng,Len(rng))

    will miraculously turn rng into a string.

    0 讨论(0)
  • 2020-12-10 21:23

    Any one of these functions will do it for you.

    Function ConCatRange2(CellBlock As Range) As String
    'for non-contiguous cells =ccr((a1:a10,c4,c6,e1:e5))
    Dim Cell As Range
    Dim sbuf As String
    For Each Cell In CellBlock
    If Len(Cell.Text) > 0 Then sbuf = sbuf & Cell.Text & ","
    Next
    ConCatRange2 = Left(sbuf, Len(sbuf) - 1)
    End Function
    

    OR

    Function mergem(r As Range) As String
    mergem = r.Cells(1, 1).Value
    k = 1
    For Each rr In r
        If k <> 1 Then
            mergem = mergem & "," & rr.Value
        End If
        k = 2
    Next
    End Function
    

    OR

    Function spliceUm(r As Range) As String
    spliceUm = ""
    For Each rr In r
    spliceUm = spliceUm & rr.Value & ";"
    Next
    End Function
    
    0 讨论(0)
提交回复
热议问题