VBA新手求助:如何按指定列复制Excel指定行数据
Excel VBA 指定行+指定列数据复制方案
你当前代码只复制s.no列的原因是:cellFrom1和cellTo1返回的是$A$2、$A$20这类带A列的地址,拼接后范围是A列的连续行,自然只提取了s.no列。要实现提取reg. no、name、Year这三列的指定行数据,给你两种实用方案:
方案1:直接指定列范围(适合列位置固定的情况)
假设reg. no对应B列、name对应C列、Year对应D列,直接拼接列字母+行范围即可:
' 定义起始行和结束行(从单元格读取行号) Dim startRow As Long, endRow As Long startRow = Sheets("I yr").Range("N4").Row ' 提取$A$2中的行号2 endRow = Sheets("I yr").Range("O4").Row ' 提取$A$20中的行号20 ' 复制B-D列的指定行数据到final表的B8起始位置 Sheets("I yr").Range("B" & startRow & ":D" & endRow).Copy _ Destination:=Sheets("final").Range("B8")
- 目标位置只需要写起始单元格
B8,Excel会自动匹配复制区域的大小,不用手动写死B8:B37,避免范围不匹配。
方案2:通过列标题找列号(适合列位置可能变动的情况)
如果以后表格列顺序调整,这个方案不用改代码,通过第一行的列标题自动定位列:
Dim wsSource As Worksheet, wsDest As Worksheet Dim colRegNo As Long, colName As Long, colYear As Long Dim startRow As Long, endRow As Long ' 绑定工作表对象,简化代码书写 Set wsSource = ThisWorkbook.Sheets("I yr") Set wsDest = ThisWorkbook.Sheets("final") ' 读取行范围(从N4、O4提取行号) startRow = wsSource.Range("N4").Row endRow = wsSource.Range("O4").Row ' 查找列标题对应的列号(假设标题在第1行,若不在则改Rows(1)为标题行号) colRegNo = wsSource.Rows(1).Find(What:="reg. no", LookIn:=xlValues, LookAt:=xlWhole).Column colName = wsSource.Rows(1).Find(What:="name", LookIn:=xlValues, LookAt:=xlWhole).Column colYear = wsSource.Rows(1).Find(What:="Year", LookIn:=xlValues, LookAt:=xlWhole).Column ' 合并三列的指定行范围,复制到目标位置 Union(wsSource.Range(wsSource.Cells(startRow, colRegNo), wsSource.Cells(endRow, colRegNo)), _ wsSource.Range(wsSource.Cells(startRow, colName), wsSource.Cells(endRow, colName)), _ wsSource.Range(wsSource.Cells(startRow, colYear), wsSource.Cells(endRow, colYear))).Copy _ Destination:=wsDest.Range("B8")
注意事项
- 如果N4、O4的单元格值是纯数字(比如直接写2、10,不是
$A$2),把.Row改成.Value即可。 - 确保列标题拼写完全一致,
Find函数是精确匹配的。
内容的提问来源于stack exchange,提问作者Sahul
相关产品推荐
相关产品推荐

