[英]Macro for selecting from multiple columns
I need help on macros in Excel. 我需要有关Excel中宏的帮助。 I have a table in Excel (example attached). 我在Excel中有一张表格(附有示例)。
I need columns A, E and G from source sheet, after last row i need A,E and H , after last row A,E and I and so on. 我需要源工作表中的A,E和G列,最后一行之后,我需要A,E和H,最后一行A,E和I之后,依此类推。 Means Column A and E will be constant, only third column will change until column K. In vertical manner. 意味着A列和E列将保持不变,只有第三列会发生变化,直到K列为止。以垂直方式。
Source data: 源数据:
A B C D E F G H I J K NAME AGE CITY STATE COUNTRY CODE PART DUEDATE VEND COMM QTY
Target: 目标:
A E G A E H A E I A E J A E K
EDIT: Code I am trying: 编辑:我正在尝试的代码:
Sub Mosaic()
With ws
'Get the last row and last column
lRow = .Range("A" & .Rows.Count).End(xlUp).Row
lCol = .Cells(1, .Columns.Count).End(xlToLeft).Column
End With
With ws2
'Get the last row and last column
lRow2 = .Range("A" & .Rows.Count).End(xlUp).Row
lCol2 = .Cells(1, .Columns.Count).End(xlToLeft).Column
End With
'Save the range from A1:Alastrow and E1:Elastrow and store as variable
Set aRng = ws.Range("A1" & lRow)
Set aRng2 = ws.Range("E1" & lRow)
'Union(AE range and G1:Glastrow)
Set gRng = ws.Range("G1" & lRow)
Set hRng = ws.Range("H1" & lRow)
Set uRng = Union(aRng, aRng2, gRng)
uRng.Copy
ws2.Range("A" & lRow2).PasteSpecial
End Sub
Finding last rows: Excel VBA select range at last row and column 查找最后一行: Excel VBA选择最后一行和最后一列的范围
You can write your own code from the help file provided 您可以从提供的帮助文件中编写自己的代码
Edit: The fix for your code: 编辑:您的代码的修复:
Sub Mosaic()
Dim aRng, eRng, extraRng as Range
Dim lRow, lRow2, CurCol as Long
With ws
'Get the last row and last column
lRow = .Range("A" & .Rows.Count).End(xlUp).Row
End With
'Save the range from A1:Alastrow and E1:Elastrow and store as variable
Set aRng = ws.Range("A1:A" & lRow)
Set aRng2 = ws.Range("E1:E" & lRow)
For CurCol = 7 to 11 'Cols G (7) to K (11)
Set extraRng = ws.Range(Cells(2, CurCol),Cells(lRow, CurCol))
'Always get the lRow2 right before pasting to ensure you have the last row.
'Get the last row of destination sheet
lRow2 = ws2.Range("A" & ws2.Rows.Count).End(xlUp).Row + 1
aRng.Copy
ws2.Range("A" & lRow2).PasteSpecial
eRng.Copy
ws2.Range("B" & lRow2).PasteSpecial
extraRng.Copy
ws2.Range("C" & lRow2).PasteSpecial
Next CurCol
End Sub
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.