简体   繁体   中英

Excel - Insert formula in empty cell

I want to insert a value on empty cell and this value multiplies automatically by 2.

Is it possible?

For example:

I set the cell value = 2. When I hit enter, it should change to 4 automatically.

How can I do this?

I think the only way is to use VBA and listen to the worksheet_change event

Private Sub Worksheet_Change(ByVal Target As Range)
  Target.Value = Target.Value * 2
End Sub

You would use an event macro. Here is an example for cell B9

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim B9 As Range, rInt As Range
    Set B9 = Range("B9")
    Set rInt = Intersect(B9, Target)
    If rInt Is Nothing Then Exit Sub
    Application.EnableEvents = False
        B9.Value = 2 * B9.Value
    Application.EnableEvents = True
End Sub

Because it is worksheet code, it is very easy to install and automatic to use:

  1. right-click the tab name near the bottom of the Excel window
  2. select View Code - this brings up a VBE window
  3. paste the stuff in and close the VBE window

If you have any concerns, first try it on a trial worksheet.

If you save the workbook, the macro will be saved with it. If you are using a version of Excel later then 2003, you must save the file as .xlsm rather than .xlsx

To remove the macro:

  1. bring up the VBE windows as above
  2. clear the code out
  3. close the VBE window

To learn more about macros in general, see:

http://www.mvps.org/dmcritchie/excel/getstarted.htm

and

http://msdn.microsoft.com/en-us/library/ee814735(v=office.14).aspx

To learn more about Event Macros (worksheet code), see:

http://www.mvps.org/dmcritchie/excel/event.htm

Macros must be enabled for this to work!

EDIT#1:

To process a range of cells, remove the original macro and use this one instead:

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim B9 As Range, rInt As Range, r As Range
    Set B9 = Range("B2:M14")
    Set rInt = Intersect(B9, Target)
    If rInt Is Nothing Then Exit Sub
    Application.EnableEvents = False
        For Each r In rInt
            r.Value = 2 * r.Value
        Next r
    Application.EnableEvents = True
End Sub

或使用“特殊粘贴-乘以”特定单元格。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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