设置范围仅产生第一行数据

时间:2018-01-08 06:04:26

标签: excel excel-vba loops range with-statement vba

我正在执行循环浏览文件夹并从每个工作簿中相应地收集一系列数据的功能。我的代码能够运行,但为什么它只复制所选范围的第一行。

  

要复制的范围:I80:I83。仅复制I80

enter image description here

代码低于

Dim lastRow As Range, rng1 As Range, lastrow2 As Range, rng2 As Range

With ThisWorkbook.Sheets(1)
Set rng1 = Worksheets(2).Range("I80:I83")
Set rng2 = Worksheets(2).Range("I1")

Set lastRow = .Range("B" & .Rows.Count).End(xlUp)
lastRow.Offset(1, 0).Resize(rng1.Columns.Count, rng1.Rows.Count) = rng1.Value


Set lastrow2 = ThisWorkbook.Worksheets("Sheet1").Cells(ThisWorkbook.Worksheets("Sheet1").Rows.Count, "A").End(xlUp)
lastrow2.Offset(1, 0).Resize(rng2.Rows.Count, rng2.Columns.Count) = rng2.Value
End With

代码输出 enter image description here

提前致谢(:

1 个答案:

答案 0 :(得分:1)

您的行和列调整大小是后退的。

lastRow.Offset(1, 0).Resize(rng1.Rows.Count, rng1.Columns.Count) = rng1.Value

如果您打算将4行数据写入4列,则需要转置数组。

lastRow.Offset(1, 0).Resize(rng1.Columns.Count, rng1.Rows.Count) = application.transpose(rng1.Value)

您可能还想将多个值放入A列。

lastrow2.Offset(1, 0).Resize(rng1.Rows.Count, rng1.Columns.Count) = rng2.Value