简体   繁体   English

在VBA Excel 2010中根据另一个单元格的值设置一个单元格的值

[英]Set value of a cell based on another cell's value in VBA Excel 2010

I want to set a value for a cell [S12] in a sheet called "AlphaPackage_2017" based on the other cell's value [S3] . 我想基于另一个单元格的值[S3]名为“ AlphaPackage_2017”的工作表中的单元格[S12]设置值。

checking should follow the value in cell [S3] for any changing value and update immediately the value in cell [S12] . 检查应遵循单元格[S3]中的值是否有任何更改的值,并立即更新单元格[S12]的值。

I wrote the below code: 我写了下面的代码:

Do
    If S3.Value > 6 Then
        S12 = 20
    Else
        S12 = 7
    End If
Loop

the code does not work correctly, any advise is appreciated ... and also where the code should be write: in Module or in Page? 代码无法正常工作,不胜感激...以及将代码写在何处:在模块中还是在页面中?

Add the code below in the Worksheet_Change event of "AlphaPackage_2017" sheet. 在“ AlphaPackage_2017” Worksheet_Change事件中添加以下代码。

Private Sub Worksheet_Change(ByVal Target As Range)

' run the code below only if a value in cell "S3" is changed
If Not Intersect(Target, Range("S3")) Is Nothing Then

    Select Case Target.Value ' <-- check the value of Range("S3")
        Case Is > 6
            Range("S12").Value = 20
        Case Else
            Range("S12").Value = 7
    End Select
End If

End Sub

Follow screen-shot below where to add this code (just in case you haven't used a Worksheet event before): 按照下面的屏幕快照在何处添加此代码(以防万一之前您没有使用过Worksheet事件):

在此处输入图片说明

In the code module of the AlphaPackage_2017 worksheet, write this routine: AlphaPackage_2017工作表的代码模块中,编写以下例程:

Private Sub Worksheet_Change(ByVal Target As Range)
    If Target.Address(0, 0) = "S3" Then
        Me.Range("S12").Value = IIf(Target.Value > 6, 20, 7)
    End If
End Sub

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM