提供给我的目标时,最后一行定义是无效的限定符

只需要一个简单的函数来查找最后一行,然后复制单元格到目的地

Sub CMS() ' ' CMS Macro ' Dim LastRow As Long With ActiveSheet LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row End With Worksheets("Sheet5").Range("B2").Copy _ Destination:=LastRow.Range("B1") Worksheets("Sheet5").Range("A2").Copy _ Destination:=LastRow.Range("B2") Worksheets("Sheet5").Range("B4:R4").Copy _ Destination:=LastRow.Range("C2") End Sub 

我已经从这个Ron De Bruin样本中得到了它

 Sub LastRowInOneColumn() 'Find the last used row in a Column: column A in this example Dim LastRow As Long With ActiveSheet LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row End With MsgBox LastRow End Sub 

并从Excel VBA文档复制

 Worksheets("Sheet1").Range("A1:D4").Copy _ destination:=Worksheets("Sheet2").Range("E5") 

然而,我收到我的LastRow在我的目的地是一个无效的限定符,我怎么能解决这个问题?

你有LastRow声明为一个Long

 Dim LastRow As Long 

…但是,然后尝试像使用Range对象一样使用它:

 LastRow.Range("B1") 

改用Cells

 Dim LastRow As Long With ActiveSheet LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row Worksheets("Sheet5").Range("B2").Copy _ Destination:=.Cells(LastRow, 2) Worksheets("Sheet5").Range("A2").Copy _ Destination:=.Cells(LastRow + 1, 2) Worksheets("Sheet5").Range("B4:R4").Copy _ Destination:=.Cells(LastRow + 1, 3) End With 

注意 – 你的预定目的地不清楚,所以上面的地址可能是错误的(我不知道什么B2等应该意味着参考一行)。 这将至less让你通过编译错误。

你最好使用Find而不是xlUp方法。

  • 在隐藏的行上工作( xlUp跳过它们)
  • 迎合空白区域( xlUp错过全部或空列作为边缘情况 – 所以需要进一步处理)

 Sub LastRowInOneColumn2() Dim rng1 As Range Set rng1 = ActiveSheet.Columns(1).Find("*", ActiveSheet.[a1], xlFormulas) If Not rng1 Is Nothing Then MsgBox "last row is " & rng1.Row Else MsgBox "column is blank" End If End Sub 

你可以使用“公式”和“帮手列”的方法:

 Sub main() With Worksheets("Data") '<--| reference your worksheet With .Range("A:A").SpecialCells(xlCellTypeConstants, xlTextValues).Offset(, .UsedRange.Columns.Count) '<--| reference its column A cells with "constant" text values offset to the first not-used column .FormulaR1C1 = "=IF(MID(RC[-" & .Column - 1 & "],6,1)=""C"",1,"""")" '<--| place a formula returning "1" if the 6th character of corresponding column A cell value is "C" .SpecialCells(xlCellTypeFormulas, xlNumbers).Offset(, -.Column + 1).Font.Color = vbRed '<-- select all cells whose formula returned "1" and color corresponding column A cell .ClearContents End With End With End Sub