Change the value of cell based on the value inputted

大憨熊 提交于 2019-12-25 12:25:16

问题


I'm trying to create a formula statement based on what the user enters into the cell. If a user enters a 0, 1 or 2, the value of THE SAME cell needs to change. For example:

if a user enters "1" into cell E2, it needs to change to "2500"
if a user enters "0" into cell E2, it needs to stay at 0
if a user enters "2" into cell E2, it needs to change to "5000"

Is this possible to achieve?
If so, what formula is necessary? I've tried different ways without luck, because I keep getting a circular loop error. Does that mean this is not possible?
Possibly with VBA?


回答1:


For example:

=VLOOKUP(A8,$C$1:$D$3,2,0)  

in A9 will respond to the trigger value in blue based on a little lookup table as shown in the box.

With validation, in A1, Data, Data Validation, Data Validation..., Settings, Allow List, Source 0,2500,5000 OK. This will create the little drop down arrow which when clicked will open a little window from which only one of your three specified values may be chosen.




回答2:


You will have to attack this problem with some VBA; specifically a Worksheet_Change event macro. Formulas cannot rewrite the cell that they are in if you over-type them with a value.

Right-click the worksheet's name tab and choose View Code. When the VBE opens, paste the following into the worksheet code pane titled something like Book1 - Sheet1 (Code).

Private Sub Worksheet_Change(ByVal Target As Range)
    If Not Intersect(Target, Range("E2")) Is Nothing Then
        On Error GoTo bm_Safe_Exit
        Application.EnableEvents = False
        With Range("E2")
            Select Case .Value2
                Case 0
                    'do nothing
                Case 1
                    .Value = 2500
                Case 2
                    .Value = 5000
                Case Else
                    'possibly clear the cell contents as undesirable
                    '.ClearContents
            End Select
        End With
    End If

bm_Safe_Exit:
        Application.EnableEvents = True
End Sub

I've left a commented code line to remove any entry that is not a 0, 1 or 2. Uncomment it if that is the preferred behavior.

Tap Alt+Q to return to the worksheet. Typing any of the three values into E2 should have the desired results.

Note that Application.EnableEvents property is temporarily turned off. This is because you are changing a value on the worksheet and want to avoid initiating another event that will attempt to have the routine walk on top of itself.



来源:https://stackoverflow.com/questions/21862981/change-the-value-of-cell-based-on-the-value-inputted

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!