[英]Showing Error in Range of Auto fill command by giving range of Active cell to Last row of the column
[英]How to auto fill the column of the active cell till the last row
嘗試執行以下代碼:
ActiveCell.Offset(1, 0).Select 'Noting but F2
ActiveCell.FormulaR1C1 = "=LEFT(RC[-1],4)"
' find last row with data in column "A"
lastRow = Cells(Rows.Count, "A").End(xlUp).Row
' copying the formula from "F2" all the way to the last cell
ActiveCell.AutoFill Destination:=Range(ActiveCell.EntireColumn & lastRow), Type:=xlFillDefault
它給出了一個錯誤,說類型不匹配。
但是當我嘗試時:
ActiveCell.AutoFill Destination:=Range("F2:F" & lastRow), Type:=xlFillDefault
它工作正常,但我不希望 F2:F 在那里,因為我不知道將來會出現哪一列。
要回答您的問題,您沒有指定正確的范圍。 正如您所說,可以指定一個簡單的范圍
使用字符串格式Range("A1:B4")
,其中A1
和B4
是范圍的兩個對角。
使用兩個角作為單元格,例如Range( Cells(1,1), Cells(4,2) )
其中Cells(1,1)
是A1
而Cells(4,2)
是B4
所以你可以寫
ActiveCell.AutoFill Destination:=Range(Cells(2, ActiveCell.Column), Cells(lastRow, ActiveCell.Column)), Type:=xlFillDefault
為了達到您的目標,您也可以避免使用自動填充。 FormulaR1C1 格式允許您使用“相對”單元格偏移/地址編寫公式。 因此,在自動填充之后,desired 列中的所有單元格都將具有相同的 FormulaR1C1。 然后您可以避免使用自動填充並為整個列手動設置相同的 FormulaR1C1。
所以你可以寫一個更簡單的代碼:
lastRow = Cells(Rows.Count, "A").End(xlUp).Row
Range(Cells(1, ActiveCell.Column), Cells(lastRow, ActiveCell.Column)).FormulaR1C1 = "=LEFT(RC[-1],4)"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.