我有一个 VBA 代码,可以在满足条件时将一行中的某些单元格复制到另一个工作表中。
问题是,这仅适用于第一张表上的数据从 A 列开始,但出于美观原因我希望我的数据从 B 列开始。
这是我编写的代码,仅当我的数据从 A 列开始时才有效。
Private Sub CommandButton1_Click()
Dim lastrow As Long, erow As Long
'to check the last filled row on sheet named one
lastrow = Worksheets("one").Cells(Rows.Count, 1).End(xlUp).Row
For i = 2 To lastrow
If Worksheets("one").Cells(i, 3).Value = "Mobile" Then
Worksheets("one").Cells(i, 1).Copy
erow = Worksheets("two").Cells(Rows.Count, 1).End(xlUp).Row
Worksheets("one").Paste Destination:=Worksheets("two").Cells(erow + 1, 1)
Worksheets("one").Cells(i, 3).Copy
Worksheets("one").Paste Destination:=Worksheets("two").Cells(erow + 1, 2)
End If
Next i
End Sub
我需要对我的代码进行哪些修改才能在 A 列为空的情况下运行?我假设我需要更改以下内容;
If Worksheets("one").Cells(i, 3).Value = "Mobile" Then to If Worksheets("one").Cells(i, 4).Value = "Mobile" Then
Worksheets("one").Cells(i, 3).Copy to Worksheets("one").Cells(i, 4).Copy
然而,这些修正仍然不起作用。
您对需要进行的可疑更改的想法是正确的,但您的代码在“lastrow =”行失败,因为它仍在查找 A 列中最后使用的单元格。
因此,您需要更改:
lastrow = Worksheets("one").Cells(Rows.Count, 1).End(xlUp).Row
至
lastrow = Worksheets("one").Cells(Rows.Count, 2).End(xlUp).Row
然后检查并更改其余的行,正如您正确怀疑需要做的那样。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句