使用vba将范围值复制到变体中
我在macros中有以下代码,但是当我运行它时,它只复制单元格B2中的值,而不是从B2:D2的整个值范围,如我在下面的代码的第5行中指定的。
Sub copying() Dim calval as variant With worksheets("sheet1") Set calval=.Cells(Rows.Count,"B").End(xlUp).Offset(2,3) calval.value=Range("B2:D2").Value 'copy range of values End With End Sub
这是单元格B2:D2中的数据
21.7 21.3 22.4
有人可以告诉我如何让calval被赋予B2:D2的全部值,而不仅仅是B2中的值。
这里有一些问题。 首先,当复制到变体时,它们不是对象,所以你不需要使用set。 他们也没有范围,因为他们的变数。 您还需要将该值复制到变体,然后才能将其设置为输出范围,以便顺序稍有偏差。 以下代码将起作用:
Sub Copying() Dim calval as Variant 'Read it in from the worksheet With Worksheets("Sheet1") calval=.Range("B2:D2").value 'Set it back to the dsired range using the bounds of the variant instead of hardcoding. .Range(.Cells(Rows.Count,"B").End(xlUp).Offset(2,3), .Cells(Rows.Count,"B").End(xlUp).Offset(1 + UBound(calval, 1), 2 + UBound(calval, 2))).Value = calval End With End Sub
我明白你已经接受了一个答案,这里是另一种方法来实现你所需要的:使用WorkSheetFunction.Transpose
方法。
Dim calval as Variant '--- Range("B2:D2").Value calval = WorkSheetFunction.Transpose(Sheets(1).Range("B2:D2").Value)
您可以根据自己的需要自由使用, offset
, resize
。 例如扩大你的范围到B12
calval = WorkSheetFunction.Transpose(Sheets(1).Range("B2:D2").Resize(10).Value)