vba - VBA 将动态范围从一个工作表复制/粘贴到另一个工作表
问题描述
我正在尝试从wsCL2
Column中复制数据,A
从单元格开始A2
到数据结束时;行数可以变化。
我想从该列中的下一个空单元格粘贴到A
,coSummary
列中。
Sub Test()
Dim wb As Workbook
Dim wsCL2 As Worksheet
Dim summary As Worksheet
Dim colLastRow As Long
Dim summaryLastRow As Long
Set wb = ActiveWorkbook
Set wsCL2 = wb.Sheets("Tocopyfrom")
Set summary = wb.Sheets("Summary")
'Defining last row of data in Colliers
summaryLastRow = summary.Cells(Rows.Count, 1).End(xlUp).Row
colLastRow = wsCL2.Cells(Rows.Count, 1).End(xlUp).Row
summary.Cells(10, 10).Value = colLastRow
summary.Cells(11, 10).Value = summaryLastRow
'Copying range from Colliers to Summary Page (***ERROR HERE***)
wsCL2.Range(Cells(2, "A").Address(), Cells(colLastRow, "A")) _
.Copy summary.Cells(summaryLastRow + 1, "A")
colLastRow = summary.Cells(Rows.Count, 1).End(xlUp).Row
End Sub
尝试该Copy
方法时有时会抛出错误;其他时候它会正确执行。
我怀疑这与刷新 value 的summaryLastRow
值或与D
?
谢谢!
解决方案
您在这行代码中遇到问题:
wsCL2.Range(Cells(2, "A").Address(), Cells(colLastRow, "A")).Copy summary.Cells(summaryLastRow + 1, "A")
您使用了很多“单元”,它们不引用 wsCL2 而是引用您的 ActiveSheet,这可能不是您想要的。这是正确的方法:
wsCL2.Range(wsCL2.Cells(2, "A").Address(), wsCL2.Cells(colLastRow, "A")).Copy summary.Cells(summaryLastRow + 1, "A")
为了更好地理解,这就是您的代码实际所说的:
wsCL2.Range(ActiveSheet.Cells(2, "A").Address(), ActiveSheet.Cells(colLastRow, "A")).Copy summary.Cells(summaryLastRow + 1, "A")
编辑:我也不确定你如何使用这些引用一次 .Address: Cells(2, "A").Address() 和下一个没有: Cells(colLastRow, "A") 更好的方法我认为参考范围是仅使用数字:
wsCL2.Range( wsCL2.Cells(2,1), wsCL2.Cells(colLastRow,1) )
最终编辑: 另一件事,如果您厌倦了编写 wsCL2。
with wsCl2
.Range( .Cells(2,1), .Cells(colLastRow,1) )
end with
推荐阅读
- mysql - Rails 6.1 where.missing 自连接
- c++ - 指向函数的向量
- next.js - 如何将 blurha.sh 与新的 Next.JS 图像组件一起使用
- html - srcset / sizes - 无法响应 img 工作
- php - 教义——三表关系
- html - 如何在不使用固定的情况下将页脚粘贴到页面底部
- c# - 无法使用 C# 从 .net 控制台应用程序连接 mongoDB atlas API
- flutter - 当它们由 StreamBuilder 构建时,如何将 IconButton onPressed 事件与 TextField 链接
- django - 将 pk 表单 URL 分配给模型的相关字段
- xml - XSLT 转换后的非法字符问题