excel - Copy data to sheet named in column header and cell named at beginning of row, then loop
问题描述
I have some production data in a table on my Source worksheet. In the header of each column is the name of the Destination worksheet, where the data in that column is to be pasted. In Column A at the beginning of each row is the destination column on the destination worksheet; and in Column B is the destination row. Column C concatenates the two to display the cell name, e.g, T138, which would be the destination cell on the destination worksheets. I haven't been a member long enough to embed an image in this post, but there is an pic of the table here:
So each datum on the Source worksheet is to be copied and then pasted to the worksheet named in the column header and the cell named in column C at the beginning of the row (or alternatively, in the column named in Col.A and the row named in Col.B) Then the script should loop back through the rest of the data cells and do the same for each of them: copy data, paste to sheet specified in column header and cell specified at the beginning of the row in Col.C.
Even though I am a total beginner, I actually thought this would be a fairly simple matter. But I haven't been able to figure out how to do this. I've tried various scripts, but none of them even began to do the job, and they really aren't even worth displaying here. I was hoping someone could point me in the right direction. Worse yet, none of my extensive searches have turned up anything like what I want to do. Maybe I just haven't used the right search terms. "Variable" seems to have gotten the closest to useable search results, but not exactly.
Here is an image of what one of the destination sheets looks like, in relevant part:
Here's a better image:
解决方案
This code will Loop over each cell in the range of G3 to J and LastRow. Copying the cell if it's numeric to the sheet based on the column header and the cell from column C.
Public Sub MoveData()
Dim rcell As Range, rng As Range
LastRow = ActiveSheet.UsedRange.Rows.Count + ActiveSheet.UsedRange.Rows(1).Row - 1
'MsgBox LastRow
Set rng = Application.ActiveSheet.Range("G3:J" & LastRow)
For Each rcell In rng.Cells
If Not Len(rcell.Value) = 0 Then
'MsgBox rcell.Value
Header = rcell.Offset(1 - rcell.Row).Value
'MsgBox Header
Set DestSheet = ThisWorkbook.Sheets(Header)
Set DestCell = ActiveSheet.Range("C" & rcell.Row)
'MsgBox DestCell
Application.ActiveSheet.Range(rcell.Address).Copy Destination:=Sheets(Header).Range(DestCell)
End If
Next rcell
End Sub
推荐阅读
- javascript - 打印 div 而不打开额外的弹出窗口
- php - 会话持续时间 24 小时
- objective-c - 如何将 Objective-C 中 iPhone 应用程序中的数据共享到 Google 表格
- javascript - 如何在 Javascript 中动态更新蛇游戏中的蛇?
- java - 反应堆核心 - 单声道 - onErrorFlatmap
- vba - Excel VBA,循环求和,然后用每个新值重新计算
- css - 使用 Bootstrap 想要做出响应式的两列表单
- c++ - 使用向量为参数化构造函数初始化对象数组
- python - 为什么我不能在`file`迭代器上手动调用`next`?
- python-3.x - 使用 Flask APScheduler 动态调度作业