改变X个细胞的函数

问题描述 投票:0回答:1

所以,我试图创建一个函数,每当我手动更改单元格的值时,该函数都会自动更新。它应该像这样工作:The MAX value defines the max value of this list

and whenever i change it, the list changes too

我可以使用子流程来完成此操作,但它只能手动更新。所以我想我可以将它作为一个函数并在随机单元格中使用它,它会自动更新,但它不起作用:

Function lista_auto(n)

For i = 2 To n
Range("E" & i) = i - 1

listaauto = Null

End Function

Error

有人有办法解决这个问题吗?还是根本不可能?

excel vba
1个回答
0
投票
  • 使用
    Worksheet_Change
    事件代码
  • 右键单击工作表选项卡,选择
    View Code
    并将代码粘贴到代码窗口中

微软文档:

Range.Offset 属性 (Excel)

Range.Resize 属性 (Excel)

Is数值函数

工作表.更改事件(Excel)

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim lastCell As Range
    Const START_CELL = "E2"
    With Target
        If .Address(0, 0) = "C2" Then
            If Not VBA.IsNumeric(.Value) Then Exit Sub
            Set lastCell = Range("E" & Me.Rows.Count).End(xlUp)
            If Len(.Value) = 0 Then
                Me.Range(START_CELL, lastCell).ClearContents
            End If
            If lastCell.Value = .Value Then Exit Sub
            Application.EnableEvents = False
            If lastCell.Value < .Value Then
                With lastCell.Offset(1).Resize(.Value - lastCell.Value)
                    .Formula = "=Row()-" & Range(START_CELL).Row - 1
                    .Value = .Value
                End With
            Else
                lastCell.Offset(.Value - lastCell.Value + 1).Resize(lastCell.Value - .Value).ClearContents
            End If
        End If
        Application.EnableEvents = True
    End With
End Sub

© www.soinside.com 2019 - 2024. All rights reserved.