Making Excel functions affect 'other' cells

前端 未结 6 1205
没有蜡笔的小新
没有蜡笔的小新 2020-12-03 13:07

Let\'s say that I create a Sub (not a function) whose mission in life is to take the active cell (i.e. Selection) and set an adjacent cell to some value. This works fine.

6条回答
  •  一整个雨季
    2020-12-03 13:39

    Here's an easy VBA workaround that works. For this example, open a new Excel workbook and copy the following code into the code area for Sheet1 (not ThisWorkbook or a VBA Module). Then go into Sheet1 and put something into one of the upper-left cells of the worksheet. If you type a number and hit Enter, then the cell to the right will be updated with 4 times the number, and the cell background will become light-blue. Any other value causes the next cell to be cleared. Here's the code:

    Dim busy As Boolean
    Private Sub Worksheet_Change(ByVal Target As Range)
      If busy Then Exit Sub
      busy = True
      If Target.Row <= 10 And Target.Column <= 10 Then
        With Target.Offset(0, 1)
          If IsNumeric(Target) Then
            .Value = Target * 4
            .Interior.Color = RGB(212, 212, 255)
          Else
            .Value = Empty
            .Interior.ColorIndex = xlColorIndexNone
          End If
        End With
      End If
      busy = False
    End Sub
    

    The subroutine captures all cell change events in the sheet. If the row and column are both <= 10, then the cell to the right is set to 4 times the changed cell if the value is numeric; otherwise the cell to the right is cleared.

提交回复
热议问题