Excel范围到平面string

我想读一个Excel范围到一个stringtypes的variables。

目前我已经完成了一个工作。 我将范围复制到剪贴板,并使用ReadClipBoard函数将剪贴板作为赋值给variables。 这种方法效率不高,有些时候由于VBA的剪贴板问题而导致错误。

解决方法代码:

  Dim variable as string Range("A1:C5").Copy variable = ReadClipBoard()'Function that returns clipboard text 

有没有更好的方法来做到这一点?

这将把每一行变成一个制表符分隔的string,整个范围变成一行分隔的string。

 Public Function RangeToText(ByRef r As Range) Dim vaData As Variant Dim aOutput() As String Dim i As Long Dim wf As WorksheetFunction Set wf = Application.WorksheetFunction 'Put range into a two dim array vaData = r.Value 'Make one dim array the same number of rows ReDim aOutput(1 To UBound(vaData, 1)) 'Make strings With tabs out of each row 'and put into one dim array For i = LBound(vaData, 1) To UBound(vaData, 1) aOutput(i) = Join(wf.Index(vaData, i), vbTab) Next i 'join all the strings into one multi-line string RangeToText = Join(aOutput, vbNewLine) End Function 

在即时窗口中

 ?rangetotext(sheet1.Range("A1:C5")) Here Here Here is is is some some some column 1 column 2 column 3 text text text 

Index工作表函数用于一次只处理一行,因为Join需要一个一维数组

如果您正在读取多个单元格,则该variables将是一个数组例如:

 Sub ArrayDemo() Dim r As Range Set r = Range("A1:C5") variable = r End Sub 

几乎相当于:

 Sub ArrayDemo2() Dim r As Range Set r = Range("A1:C5") Dim variable(1 To 5, 1 To 3) As Variant For i = 1 To 5 For j = 1 To 3 variable(i, j) = Cells(i, j).Value Next j Next i End Sub 

天真的方法是将所有的内容连接成一个string,这对你来说可以吗?

 Function ConcatCells(r as range, optional sep as string) as string dim c as range dim s as string s="" if sep is missing then sep=" " for each c in r.cells s = s & c & sep next c s=left(s, len(s) - len(sep)) ConcatCells=s end sub