Excel,VBA和移动行

我是菜鸟:VBA和macros(创build或运行)。 我需要一些帮助,这些代码可以帮助我从一个电子表格复制一行到另一个电子表格,并将其保留在原始表格中,并以某种方式进行标记(我认为),或者确保将来不会复制。 我发现了一些关于移动行的post,大部分依赖于date条目,但这不适合我的目的。 我的工作表有一个下拉数据validation的列(H) – 从下拉列表单元格的任何条目将标识行作为一个复制到下一个工作表。 但是,也有一个列(J),其中数据input是可选的,我不希望该行在复制之前给予用户进入该列的机会,以便它的内容也复制(或者也许那是一组独立的代码?)。 应将复制到新电子表格的行插入到下一个可用行中。 感谢您提供任何帮助和指导。

好的 – 与信息。 我从你的post收集,我有以下几点:

Sub copyRows() Dim xRow As Integer, xCol As Integer, lastCol As Integer Dim dataValidation As Range, rowToCopy As Integer, copyRange As Range, destRange As Range Dim copyWSRow As Integer, jColValue As String Dim origWS As Worksheet, copyWS As Worksheet Set origWS = ActiveSheet ' Edit these two lines as needed. If you have the "copy" worksheet already, comment out the first line ' and then change the 'Sheets("Copy")' to 'Sheets("_____")' Worksheets.Add(after:=Worksheets(1)).Name = "Copy" Set copyWS = Sheets("Copy") origWS.Activate Set dataValidation = origWS.Cells(1, 8) ' Cell H1 has your data validation. Change this as necessary rowToCopy = dataValidation.Value 'find the last column used, that isn't Col. H. If it's column H, assume G is the last column lastCol = origWS.Cells(1, 1).End(xlToRight).Column If lastCol = 8 Then lastCol = lastCol - 1 With origWS Set copyRange = .Range(.Cells(rowToCopy, 1), .Cells(rowToCopy, lastCol)) End With 'What's the next available row in the Copy WS? If copyWS.UsedRange.Rows.Count = 1 And copyWS.Cells(1, 1).Value = "" Then copyWSRow = 1 Else copyWSRow = copyWS.UsedRange.Rows.Count + 1 ' count the used rows, and add one to make the next blank row the row to copy to End If 'Set the destination Range With copyWS Set destRange = .Range(.Cells(copyWSRow, 1), .Cells(copyWSRow, lastCol)) End With 'Now, just copy the info over (technically, just set values equal) destRange.Value = copyRange.Value 'Now, check to see if Column J has any info - if so, add to the line we just did in the Copy WS If origWS.Cells(1, 10).Value <> "" Then jColValue = origWS.Cells(1, 10).Value copyWS.Cells(copyWSRow, 10).Value = jColValue End If ' Add note that the row was copied origWS.Cells(rowToCopy,13).Value = "Already Copied" End Sub 

一些注意事项:我已经假定最右边一列,有你想要复制的数据,将是G列 – 因为H有行值。

另外,我将H1作为具有数据validation的单元格 – 您可能需要根据需要进行编辑。

我用一些数据testing了这一点,列A到G,H1和J1是数据validation(输出数字),J1是“额外”信息。 如果您希望“额外信息”位于数据的每行,而不是一个绝对位置,只需将jColValue公式更改为jColValue = origWS.Cells(rowToCopy,10).Value

当然,如果这不起作用或需要调整,请让我知道。