提问人:Mark 提问时间:10/19/2023 最后编辑:braXMark 更新时间:10/19/2023 访问量:46
VBA 复制和粘贴范围
VBA Copy and Paste Range
问:
我有一个代码,可以根据工作表 1 列中的单元格值将行从工作表 1 复制并粘贴到工作表 2。工作表 1 有 20+ 列,但我只想在工作表 2 中包含其中的 5 列。有没有更好的方法来编写此代码,以便我可以复制并粘贴不同单元格值的部分代码?也就是说,我有 5 行代码,我想减少到 1 行。我想在工作表 2 上创建多个相互偏移的表格。列是固定的,行是可变的。目前,我必须重复代码并指定将我的表放在工作表 2 中的确切位置。
For myRow = 1 To LastRow
If (Sheets("Sheet1").Cells(myRow, "E") = "TI002768E2XA E005") Then
Set srcRange = Sheets("Sheet1").Cells(myRow, "F").Resize(1, 5)
If Application.CountA(srcRange) = 5 Then
Sheets("Sheet2").Cells(myCopyRow, "B") = Sheets("Sheet1").Cells(myRow, "E")
Sheets("Sheet2").Cells(myCopyRow, "C") = Sheets("Sheet1").Cells(myRow, "D")
Sheets("Sheet2").Cells(myCopyRow, "D") = Sheets("Sheet1").Cells(myRow, "F")
Sheets("Sheet2").Cells(myCopyRow, "E") = Sheets("Sheet1").Cells(myRow, "G")
Sheets("Sheet2").Cells(myCopyRow, "F") = Sheets("Sheet1").Cells(myRow, "H")
myCopyRow = myCopyRow + 1
End If
End If
If (Sheets("Sheet1").Cells(myRow, "E") = "TI002768E2XA E105") Then
Set srcRange = Sheets("Sheet1").Cells(myRow, "F").Resize(1, 5)
If Application.CountA(srcRange) = 5 Then
Sheets("Sheet2").Cells(myCopyRow1, "H") = Sheets("Sheet1").Cells(myRow, "E")
Sheets("Sheet2").Cells(myCopyRow1, "I") = Sheets("Sheet1").Cells(myRow, "D")
Sheets("Sheet2").Cells(myCopyRow1, "J") = Sheets("Sheet1").Cells(myRow, "F")
Sheets("Sheet2").Cells(myCopyRow1, "K") = Sheets("Sheet1").Cells(myRow, "G")
Sheets("Sheet2").Cells(myCopyRow1, "L") = Sheets("Sheet1").Cells(myRow, "H")
myCopyRow1 = myCopyRow1 + 1
End If
End If
Next myRow
答:
0赞
vbakim
10/19/2023
#1
我会使用源列和目标列的数组。然后,使用循环复制每列的值。例如,您的复制的第一部分应如下所示;
Dim srcColumns() As Variant
Dim destColumns() As Variant
Dim i As Integer
For myRow = 1 To LastRow
If Sheets("Sheet1").Cells(myRow, "E") = "TI002768E2XA E005" Then
Set srcRange = Sheets("Sheet1").Cells(myRow, "F").Resize(1, 5)
If Application.CountA(srcRange) = 5 Then
srcColumns = Array("E", "D", "F", "G", "H")
destColumns = Array("B", "C", "D", "E", "F")
For i = LBound(srcColumns) To UBound(srcColumns)
Sheets("Sheet2").Cells(myCopyRow, destColumns(i)).Value = Sheets("Sheet1").Cells(myRow, srcColumns(i)).Value
Next i
myCopyRow = myCopyRow + 1
End If
End If
上一个:Excel VBA用于选择可见行/活动表的正确代码?
下一个:隐藏列:设置范围
评论