在 VBA 中创建和转置数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24456328/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Creating and Transposing Array in VBA
提问by dutchballa
I'm hoping to load values in a range to an array and transpose that array to another location (different workbook)
我希望将某个范围内的值加载到数组并将该数组转置到另一个位置(不同的工作簿)
I am using the below forum post to get an idea of how to do it:
我正在使用下面的论坛帖子来了解如何做到这一点:
Below is the code I am working with now, and I'm getting the 1004 object defined error. Can anyone spot what I am doing wrong?
下面是我现在正在使用的代码,我收到了 1004 对象定义错误。谁能发现我做错了什么?
I did find that the code works if I do not Set tRangeArray and instead do Sheets("sheet1").Range("C12:C19).Value = Application.Transpose(MyArray)
, but I'm not sure why that's different from my code.
我确实发现如果我不设置 tRangeArray 而是执行Sheets("sheet1").Range("C12:C19).Value = Application.Transpose(MyArray)
,则代码有效,但我不确定为什么这与我的代码不同。
Sub copy_data()
Dim cRange As Range, aRange As Range, tRange1 As Range, wbk1 As Workbook, wbk2 As
Workbook
Dim MyArray() As Variant, tRangeArray As Range
Set wbk1 = ThisWorkbook
MyArray = Range("E12:L12")
Set tRangeArray = wbk1.Sheets("sheet1").Range("C12:C19")
Sheets("sheet1").Range(tRangeArray).Value = Application.Transpose(MyArray)
回答by Dmitry Pavliv
As I mentioned in comments, just use:
正如我在评论中提到的,只需使用:
tRangeArray.Value = Application.Transpose(MyArray)
Sheets("sheet1").Range(tRangeArray).Value
not working, because Range
accepts either single parameter - string with range address(not range itself): Range(addr)
, either two parameters - top left and bottom right cells: Range(cell_1,cell_2)
Sheets("sheet1").Range(tRangeArray).Value
不工作,因为Range
接受单个参数 - 带有范围地址的字符串(不是范围本身)Range(addr)
:,或者两个参数 - 左上角和右下角单元格:Range(cell_1,cell_2)
回答by robertocm
Similar, but using Resize and Ubound:
类似,但使用 Resize 和 Ubound:
Dim myarray As Variant
myarray = Array(1, 2, 3, 4, 5)
Sheets("sheet1").Range("A1").Resize(UBound(myarray), 1).Value = Application.Transpose(myarray)