我打算用两个单元格作为输入在excel中创建一个工作表。 对于前A2是一; C2是5 A2:C2 = 1:5之间的关系 C2:A2之间的关系= 1:1/5 有没有一种方法可以编写脚本来获得这种循环关系。 下次我在(A2)中键入2时,我看到单元格(C2)为10 另外,如果我在(C2)中输入40,我在(A2)中看到8
答案 0 :(得分:3)
在工作表的专用代码表中使用Worksheet_Change(右键单击工作表名称选项卡,查看代码)。
Private Sub Worksheet_Change(ByVal Target As Range)
'only A2 and C2
'If Not Intersect(Range("A2, C2"), Target) Is Nothing Then
'all of columns A and C
If Not Intersect(Range("A:A, C:C"), Target) Is Nothing Then
On Error GoTo safe_exit
Application.EnableEvents = False
Dim t As Range
For Each t In Intersect(Range("A:A, C:C"), Target)
select case t.column
case 1
t.offset(0, 2) = 5 * t.value
case 3
t.offset(0, -2) = t.value / 5
end select
Next t
End If
safe_exit:
Application.EnableEvents = true
End Sub
答案 1 :(得分:0)
您必须同时使用Worksheet_Change()
(对特定单元格值更改做出反应)和Worksheet_SelectionChange()
(在任何特定单元格值更改发生之前捕获比率)事件处理程序。
因此将以下内容放置在所需的工作表代码窗格中:
Dim ratio As Double
Private Sub Worksheet_Change(ByVal Target As Range)
On Error GoTo exitSub
Application.EnableEvents = False
Select Case Target.Address
Case "$A$2"
Range("C2").Value = ratio * Target.Value2
Case "$C$2"
Range("A2").Value = ratio * Target.Value2
End Select
exitSub:
Application.EnableEvents = True
End Sub
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Select Case Target.Address
Case "$A$2"
ratio = Range("C2") / Target.Value2
Case "$C$2"
ratio = Range("A2") / Target.Value2
End Select
End Sub