最有效的方法来重新使用任何行上的静态VBA代码

我试图让用户input一个百分比值,或者是一个小时数 – 这个未使用的选项是用一个使用已经input的macros自动填充的。

使用下面的例子,如果用户键入了25个小时,那么macro将会向B2(如B3所示)中添加一个公式来计算25%(在C2中显示的总数),如果用户将该百分比添加到单元格B2,然后用小时数填充A2(再次使用C2中显示的总数)。

在这里输入图像说明

我有macros观工作来实现这一点:

 Option Explicit Private Sub Worksheet_Change(ByVal Target As Range) Dim Cell As Range For Each Cell In Target If Cell.Address = "$A$2" Then Application.EnableEvents = False Range("B2").Formula = "=(A2/C2)*100" Application.EnableEvents = True End If Next Cell For Each Cell In Target If Cell.Address = "$B$2" Then Application.EnableEvents = False Range("A2").Formula = "=(B2*C2)/100" Application.EnableEvents = True End If Next Cell End Sub 

我现在试图build立的是在不同的行上重新使用这个更有效的方法吗?

列将保持不变,但理想情况下,它将在第2行到第100行上工作。在移动过程中,我能想到的唯一select是多次复制macros并引用单个使用的单元格。

任何指针或build议非常感谢。

要做2到100之间的所有行然后使用这个:

  1. 使用相交来确定在特定范围内改变的单元格。

  2. 在公式上使用R1C1表示法以确保正在评估同一行。

代码:

 Private Sub Worksheet_Change(ByVal Target As Range) If Not Intersect(Target, Range("A2:A100")) Is Nothing Then Application.EnableEvents = False Target.Offset(, 1).FormulaR1C1 = "=(RC[-1]/RC[1])*100" Application.EnableEvents = True End If If Not Intersect(Target, Range("B2:B100")) Is Nothing Then Application.EnableEvents = False Target.Offset(, -1).FormulaR1C1 = "=(RC[1]*RC[2])/100" Application.EnableEvents = True End If End Sub 

只要改变你的testing看看列属性,而不是使用相对引用 – 就像这样:

 Private Sub Worksheet_Change(ByVal Target As Range) Dim Cell As Range For Each Cell In Target If Cell.Column = 1 And (Cell.Row >= 2 And Cell.Row <= 100) Then Application.EnableEvents = False Cell.Offset(0, 1).FormulaR1C1 = "=(RC[-1]/RC[1])*100" Application.EnableEvents = True End If Next Cell For Each Cell In Target If Cell.Column = 2 (Cell.Row >= 2 And Cell.Row <= 100) Then Application.EnableEvents = False Cell.Offset(0, -1).FormulaR1C1 = "=(RC[1]*RC[2])/100" Application.EnableEvents = True End If Next Cell End Sub