复制由空白单元格组成的列数据

我遇到了这样一种情况:我需要复制Excel表格中的一个范围,并将其粘贴到另一个表格中。 我已经完成了以下的编码,

Dim mpn As String mpn = Application.InputBox(prompt:="Input the MPN column name:") mpn1 = mpn mpn2 = mpn1 & ":" & mpn Set currentSheet = wbSource.Worksheets(1) lastRow1 = currentSheet.Range(mpn1).End(xlDown).Row ThisWorkbook.Sheets("Sheet2").Range("F2:F" & lastRow1) = currentSheet.Range(mpn2 & lastRow1).Value 

直到列中有任何空白单元格为止,这个编码都会完好无损。 任何人都可以请帮我在这个特定的情况。

就像我在上面的评论中提到的那样,不是提示列名,而是使用.Findfind列名。 如果用户在input框中inputBlah Blah会怎么样?

正如在注释中提到的,使用xlUp而不是xlDown来查找最后一行来计算空白单元格以及其他可能遇到的问题。 看到这个

这是你正在尝试? ( 未经testing

我已经评论了代码,所以你不应该有理解它的问题。 但是,如果你这样做,然后只是回发:)

 Sub Sample() Dim mpnCol As Long Dim ColName As String, strSearch As String Dim aCell As Range Dim wbSource As Workbook Dim wbInput As Worksheet, currentSheet As Worksheet '~~> Change this to the Mpn Header strSearch = "MPN" '~~> This you have declared in your code '~~> Change as applicable Set wbSource = "Someworkbook" Set currentSheet = wbSource.Worksheets(1) Set wbInput = ThisWorkbook.Sheets("Sheet2") With currentSheet '~~> Search for the mpn header in row 1. Change as applicable Set aCell = .Rows(1).Find(What:=strSearch, LookIn:=xlValues, _ LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _ MatchCase:=False, SearchFormat:=False) If Not aCell Is Nothing Then '~~> Column Number mpnCol = aCell.Column '~~> Converting column number to column name ColName = Split(.Cells(, mpnCol).Address, "$")(1) '~~> Getting last row lRow = .Range(ColName & .Rows.Count).End(xlUp).Row '~~> Checking for excel versions. Comment this if the copying '~~> will always happen in xl2007+ versions If lRow > 65536 Then MsgBox "Are you trying to copy from xl2007 to xl2003?. The number of rows exceed the row limit" Exit Sub End If wbInput.Range("F2:F" & lRow).Value = .Range(ColName & "2:" & ColName & lRow).Value Else MsgBox strSearch & " header not found" End If End With End Sub 

要复制整个列 ,请使用.Columns()函数引用您的范围。

你可以使用像这样的东西:

 ThisWorkbook.Sheets("Sheet2").Columns("F") = currentSheet.Columns(mpn1).Value 

另一种替代方法是使用.Copy子文件并为该副本指定一个Destination

 currentSheet.Columns(mpn1).Copy Destination:=ThisWorkbook.Sheets("Sheet2").Columns("F") Application.CutCopyMode = false 

这个答案假定两个工作簿都保存在相同版本的Excel中。 如果一个工作簿是2007年以前的,一个是2007+,那么表中允许的最大行数将会不同。

在这种情况下,复制整个列不是一个选项 – 检查Siddarth的答案是为了解决这个额外的复杂问题。 他检查不同数量的行以防止错误。