【发布时间】:2015-09-24 13:04:19
【问题描述】:
又是我...我有一些代码可以从某个列(来自工作表“转换器”)复制单元格并将其粘贴到不同的列(工作表“未分配”)。然后将这些值(ID)用作参考点,将每行(记录)的其余单元格移动到我需要它的正确位置。
但是,我无法获取将 ID 连续复制到空白行中的代码,这样它们就不会覆盖前一组。我认为这与Master.Cells(rowB, colB) = yourData 行有关,但我无法弄清楚。我尝试将rowB 更改为相同的xlUp 以查找列中最后一个未使用的单元格(与lastA = Slave.Cells(Rows.Count, colA).End(xlUp).Row 一样),但我无法让它工作。有什么想法吗?
当前代码:
Private Sub CommandButton21_Click()
Dim colA As Integer, colB As Integer
Dim rowA As Integer, rowB As Integer
Dim Master As Worksheet, Slave As Worksheet 'declare both
Application.ScreenUpdating = False
Set Master = ThisWorkbook.Worksheets("Unallocated")
Set Slave = ThisWorkbook.Worksheets("Convertor")
colA = 17
colB = 29
rowA = 1
rowB = 1
lastA = Slave.Cells(Rows.Count, colA).End(xlUp).Row 'This finds the last row of the data of the column FROM which i'm copying
For x = rowA To lastA 'Loops through all the rows of A
yourData = Cells(x, colA)
Master.Cells(rowB, colB) = yourData
rowB = rowB + 1 'Increments the current line of destination workbook
Next x 'Skips to next row
For j = 1 To 5000 '(the master sheet)
For i = 1 To 5000 '(the slave sheet) 'for first 1000 cells
If Trim(Master.Cells(j, 29).Value2) = vbNullString Then Exit For 'if ID cell is blank exit
If Master.Cells(j, 29).Value = Slave.Cells(i, 17).Value Then
If IsEmpty(Slave.Cells(i, 3)) Then Exit Sub
Master.Cells(j, 2).Value = Slave.Cells(i, 3).Value 'Move all other data based on the ID
Master.Cells(j, 8).Value = Slave.Cells(i, 4).Value
Master.Cells(j, 9).Value = Slave.Cells(i, 5).Value
Master.Cells(j, 10).Value = Slave.Cells(i, 6).Value
Master.Cells(j, 11).Value = Slave.Cells(i, 7).Value
Master.Cells(j, 12).Value = Slave.Cells(i, 8).Value
Master.Cells(j, 13).Value = Slave.Cells(i, 9).Value
Master.Cells(j, 4).Value = Slave.Cells(i, 10).Value
Master.Cells(j, 23).Value = Slave.Cells(i, 11).Value
Master.Cells(j, 24).Value = Slave.Cells(i, 12).Value
Master.Cells(j, 25).Value = Slave.Cells(i, 13).Value
Master.Cells(j, 26).Value = Slave.Cells(i, 14).Value
Master.Cells(j, 27).Value = Slave.Cells(i, 15).Value
Master.Cells(j, 28).Value = Slave.Cells(i, 16).Value
If Not IsEmpty(Slave.Cells(i, 3)) Then _
Slave.Cells(i, 3).EntireRow.Delete 'deletes row after it has been copied
End If
Next
Next
Application.ScreenUpdating = True
End Sub
【问题讨论】:
-
你为什么不在同一个循环中完成所有的复制?
-
我不太确定怎么做。最初我正在研究静态值(ID)被用作移动其余数据的锚点(第二个循环)。但是现在 ID 现在只在第一张纸上,所以我认为这些需要首先传输以作为其余数据的锚点。我使用第二个循环(值),因为它似乎是将大量数据移动到我需要的正确顺序的最快方法。谢谢。
-
查看我的新答案。这将在当前工作表上逐行进行并将数据复制到另一张工作表。我们一次性完成。