Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 as much of the formatting as possible (i.e. it needs to look like a table or list, not just a string of characters). I've tried working with CStr(), as well as converting from a range to an array and then to a string, but I just get errors.

Edit: Code attempt

Dim email_answer As Integer
email_answer = MsgBox("Do you want to be emailled a copy of this schedule?", vbYesNo)
If email_answer = vbYes Then

    Dim wb As Workbook
    Dim to_send As Range
    to_send = Range("D3", "D10")

    If Val(Application.Version) < 14 Then Exit Sub

    Set wb = ActiveWorkbook
    With wb
        MailFromMacWithMail body content:=CStr(to_send), _
                    mailsubject:="Schedule", _
                    toaddress:="email address", _
                    ccaddress:="", _
                    bccaddress:="", _
                    attachment:=.FullName, _
                    displaymail:=False
    End With
    Set wb = Nothing
End If
like image 878
1937827 Avatar asked Dec 02 '22 13:12

1937827


2 Answers

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
like image 181
Wolfie Avatar answered Dec 18 '22 10:12

Wolfie


you could use this function:

Function Rang2String(rng As Range) As String
    Dim strng As String
    Dim myRow As Range
    With rng
        For Each myRow In .Rows
            strng = strng & Join(Application.Transpose(Application.Transpose(myRow.value)), "|") & vbLf
        Next
    End With
    Rang2String = Left(strng, Len(strng) - 1)
End Function

which would return a string with linefeed character as range rows separator and pipes ("|") as columns separator

like image 43
user3598756 Avatar answered Dec 18 '22 12:12

user3598756