如何将范围转换为string(VBA)?

将单元格范围转换为string的最佳方法是什么? 我有一个函数只需要一个string作为input,所以我需要将范围转换为一个string,同时保留尽可能多的格式(即它需要看起来像一个表或​​列表,而不只是一串字符) 。 我已经尝试使用CStr(),以及从范围转换为数组,然后转换为string,但我只是得到错误。

编辑:代码尝试

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 

在逗号分隔的单元格值范围内:

 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 

如果行号增加,可以添加额外的function,如插入分号而不是逗号。

要使用这个function:

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

你可以使用这个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 

这将返回一个string换行字符作为范围行分隔符和pipe道(“|”)作为列分隔符

这些function中的任何一个都会为你做。

 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 

要么

 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 

要么

 Function spliceUm(r As Range) As String spliceUm = "" For Each rr In r spliceUm = spliceUm & rr.Value & ";" Next End Function 

我知道这个问题已经快一年了,但是我发现了一个适用于我的快速解决scheme:您必须创build一个对Microsoft Forms 2.0对象库的引用来使用DataObject。

 Public Function GetStringFromRange(RNG As Range) As String Dim DOB As New MSForms.DataObject RNG.Copy DOB.GetFromClipboard GetStringFromRange = DOB.GetText End Function