我有一个电子表格,我想自动填充我添加到电子表格最后一栏的文字。
我设法找出要输入最后一列的代码。当我尝试自动填充时,我一直收到错误。
代码正在查找最后一行和列,没有任何问题。
我的代码
Sub Rename_Name_and_Two()
Dim colLast As Long
'For first row. To change rows, alter the Cells number
colLast = Cells(1, Columns.Count).End(xlToLeft).Column
' Finds the last row
Dim lastRow As Long
lastRow = Range("A" & Rows.Count).End(xlUp).Row
'Now for some data:
Cells(1, colLast + 1) = "Secondary First Name"
ActiveCell.AutoFill Destination:=Range(Selection, lastRow)
End Sub
随意指出我正确的方向。
答案 0 :(得分:0)
您应该避免使用ActiveCell
,Selection
等。
在您的第Cells(1, colLast + 1) = "Secondary First Name"
行中,您正在写下第一个空列中的文字,但您永远不会Selecting
,这就是为什么在下一行ActiveCell.AutoFill...
它&#39 ; s不一定拖动这个单元格。
您希望AutoFill
的范围应该是第一个单元格Cells(1, colLast + 1)
,直到最后一行Cells(lastRow, colLast + 1)
。
注意:您的lastRow
正在查找A列中的最后一行,如果列中包含更多行,您仍然会FillDown
到列中的最后一行甲
<强> 代码 强>
Option Explicit
Sub Rename_Name_and_Two()
Dim colLast As Long, lastRow As Long
' use With statement to fully qualify your cells and range with the worksheet
With ThisWorkbook.Sheets("Sheet1") ' modify "sheet1" to your sheet's name
' For first row. To change rows, alter the Cells number
colLast = .Cells(1, .Columns.Count).End(xlToLeft).Column
' Finds the last row (in column A)
lastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
' Now for some data:
.Cells(1, colLast + 1).Value2 = "Secondary First Name"
' drag the text untill last row (in column A)
.Cells(1, colLast + 1).AutoFill Destination:=.Range(.Cells(1, colLast + 1), .Cells(lastRow, colLast + 1))
End With
End Sub
答案 1 :(得分:0)
您实际上并不需要AutoFill
,因为您正在复制常量字符串
所以你可能想要使用:
Sub Rename_Name_and_Two()
With ActiveSheet.UsedRange ' reference currently active sheet 'UsedRange', i.e. the "rectangular" range embracing all used cells
.Offset(, .Columns.Count).Resize(, 1).Value = "Secondary First Name" ' resize referenced range (i.e. 'UsedRange') to one column only and offset it by its columns number (-> you get a one column range at the right of 'UsedRange') and assign its cells the value "Secondary First Name"
End With
End Sub