excel - 初始宏运行后,将源范围移动到下一行并复制
问题描述
最近,该社区的一位成员帮助我解决了如何为我的项目构建宏。以下宏完全按照我的意愿工作。但是,我正在尝试纠正一个手动依赖项。
源范围被预定义为特定的单元格引用(例如 A10、B10、C10、F10 ...)在我运行此宏之后,我希望源范围向下移动到下一行,以便下次调用宏时, 它复制 A11, B11, C11, F11...
请让我知道这是否可能。以下是我一直在使用的 VBA 代码:
Public Sub Update_Project_1()
' Set a reference to the source sheet
Dim sourceSheet As Worksheet
Set sourceSheet = ThisWorkbook.Worksheets("High Level Tracker")
' Set a reference to the target sheet
Dim targetSheet As Worksheet
Set targetSheet = ThisWorkbook.Worksheets("Project 1 Detailed Tracker")
' Set a reference to the source range
Dim sourceRange As Range
Set sourceRange = sourceSheet.Range("A10,B10,C10,F10,H10")
' Get last row in target sheet
Dim lastRow As Long
lastRow = targetSheet.Cells(targetSheet.Rows.Count, "A").End(xlUp).Row
' Loop through each cell in source range
Dim sourceCell As Range
For Each sourceCell In sourceRange.Cells
' Output values from source range into next empty row in target
Dim columnCounter As Long
targetSheet.Range("A" & lastRow + 1).Offset(, columnCounter).Value = sourceCell.Value
columnCounter = columnCounter + 1
Next sourceCell
End Sub
任何帮助将不胜感激,谢谢!
解决方案
您可以在源工作表中找到最后一个空行,然后将值复制到目标工作表
Public Sub Update_Project_1()
' Set a reference to the source sheet
Dim sourceSheet As Worksheet
Set sourceSheet = ThisWorkbook.Worksheets("High Level Tracker")
' Set a reference to the target sheet
Dim targetSheet As Worksheet
Set targetSheet = ThisWorkbook.Worksheets("Project 1 Detailed Tracker")
' Get last row in source sheet
Dim lastRowSource As Long
lastRowSource = sourceSheet.Cells(sourceSheet.Rows.Count, "A").End(xlUp).Row
' Define the source range address
Dim sourceRangeAddress As String
sourceRangeAddress = "A<r>,B<r>,C<r>,F<r>,H<r>"
' Replace next row in source rane
sourceRangeAddress = Replace(sourceRangeAddress, "<r>", lastRowSource)
' Set a reference to the source range
Dim sourceRange As Range
Set sourceRange = sourceSheet.Range(sourceRangeAddress)
' Get last row in target sheet
Dim lastRowTarget As Long
lastRowTarget = targetSheet.Cells(targetSheet.Rows.Count, "A").End(xlUp).Row
' Loop through each cell in source range
Dim sourceCell As Range
For Each sourceCell In sourceRange.Cells
' Output values from source range into next empty row in target
Dim columnCounter As Long
targetSheet.Range("A" & lastRowTarget + 1).Offset(, columnCounter).Value = sourceCell.Value
columnCounter = columnCounter + 1
Next sourceCell
End Sub
推荐阅读
- python - 在不使用命令行参数的情况下从 python 程序启动 celery beat
- typescript - typescript 柯里化调用结果和函数定义
- node.js - Puppeteer 不渲染存储在 AWS S3 上的图像
- android - Android按钮在第二次点击时改变颜色
- android - 应用程序启动时将导航抽屉活动设置为主要活动
- php - PHP crud更新和删除功能不起作用
- python - Python 文件 - 从 CamelCase 更改为下划线命名约定 - 有什么方法可以更快地做到这一点?
- asp.net-core - 允许在 nginx 中使用反向代理在子域上使用 cors
- php - How to set title with data from included PHP file
- python - 当 dag 中的设置显示为无时,为什么仍然每天安排一次气流作业