自动将特定单元格的VBA应用于select/列

我是VBA新手,需要一些帮助。 我发现VBA会查看活动单元格的值,并插入等于单元格中的值的行数。

我的问题是,这只适用于活动单元格,我有一个列,我希望这个过程自动化。 有谁知道我应该改变下面的代码?

Sub InsertSome() Dim i As Integer, n As Integer, m As Long n = ActiveCell.Value m = ActiveCell.Row For i = 1 To n Rows(m * i + 1).Insert Next i End Sub 

提前致谢!

你必须使用Events 。 将此代码插入到您希望工作的工作表的模块中。 每当你在C列中select一个单元格时,它都会运行。

 Private Sub Worksheet_SelectionChange(ByVal Target As Range) If Not Intersect(Target, Range("C:C")) Is Nothing And Target.Value <> "" Then '<-Change "C:C" to your column Dim i As Integer, n As Integer, m As Long n = Target.Value m = Target.Row For i = 1 To n Rows(m * i + 1).Insert Next i End If End Sub 

您可以使用其中一个Worksheet事件,如Worksheet_SelectionChangeWorksheet_Change事件。

另外,你不需要有这么多的variables,你可以使用Target对象的属性(相当于ActiveCell )。 另外 ,你可以一次添加多行(不需要For循环)。

 Private Sub Worksheet_SelectionChange(ByVal Target As Range) ' modify column "A" to your desired column If Not Intersect(Target, Range("A:A")) Is Nothing Then ' make sure the value is numeric, positive, and you select a single cell If Target.Value > 0 And Trim(Target.Value) <> "" And IsNumeric(Target.Value) And Target.Cells.Count = 1 Then ' no need for a loop to add 1 row at a time, ' just use the line below to add the number of rows in the Target (acitveCell) at once Range(Cells(Target.Row + 1, 1), Cells(Target.Row + Target.Value, 1)).EntireRow.Insert End If End If End Sub