我正在尝试将Excel范围读取为string类型的变量。
目前我已经完成了一项工作。我将范围复制到剪贴板并使用ReadClipBoard
函数读取剪贴板作为赋值给变量。此方法效率不高,有时由于VBA的剪贴板问题而导致错误。
解决方法代码:
Dim variable as string
Range("A1:C5").Copy
variable = ReadClipBoard()'Function that returns clipboard text
有更好的方法吗?
答案 0 :(得分:2)
这会将每一行转换为以制表符分隔的字符串,并将整个范围转换为以行分隔的字符串。
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
索引工作表函数用于一次只处理一行,因为Join需要一维数组
答案 1 :(得分:1)
如果您正在阅读多个单元格,那么变量将是数组例如:
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
答案 2 :(得分:0)
朴素的方法是将所有内容连接成一个字符串,对你来说还可以吗?
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