gpt4 book ai didi

excel - VBA Worksheet_Change 仅适用于一个单元格

转载 作者:行者123 更新时间:2023-12-04 22:23:15 25 4
gpt4 key购买 nike

我想先说我是 VBA 的新手,所以希望这是一个简单的解决方法。
我正在尝试使以下 VBA 代码适用于具有公式的多个单元格。效果是单元格中有一个幻影值,用户可以覆盖然后再次查看他们是否删除了它们的值。我可以让一个单元按我想要的方式工作,但第二个(以及第三个和第四个等)不起作用。如何重复同一行代码,以便效果在具有不同公式的多个单元格中重复出现?

在职的:

Private Sub Worksheet_Change(ByVal Target As Excel.Range)    
With Target
If .Address(False, False) = "F7" Then
If IsEmpty(.Value) Then
Application.EnableEvents = False
.Formula = "=IFERROR(INDEX(DATABASE!$D$2:$AG$3222,MATCH('Pricing Grid'!$B$11,DATABASE!$E$2:$E$3222,0),10),0)"
Application.EnableEvents = True
End If
End If
End With
End Sub

我的尝试(顶部工作,底部不是):
Private Sub Worksheet_Change(ByVal Target As Excel.Range)
With Target
If .Address(False, False) = "F7" Then
If IsEmpty(.Value) Then
Application.EnableEvents = False
.Formula = "=IFERROR(INDEX(DATABASE!$D$2:$AG$3222,MATCH('Pricing Grid'!$B$11,DATABASE!$E$2:$E$3222,0),10),0)"
Application.EnableEvents = True
End If
End If
End With
End Sub

Private Sub Worksheet_Change1(ByVal Target As Excel.Range)
With Target
If .Address(False, False) = "F8" Then
If IsEmpty(.Value) Then
Application.EnableEvents = False
.Formula = "=IFERROR(INDEX(DATABASE!$D$2:$AG$3222,MATCH('Pricing Grid'!$B$11,DATABASE!$E$2:$E$3222,0),9),0)"
Application.EnableEvents = True
End If
End If
End With
End Sub

最佳答案

尝试这个...

Private Sub Worksheet_Change(ByVal Target As Range)
Dim i&, j&, v, t
v = Target.Value2
If Not IsArray(v) Then t = v: ReDim v(1 To 1, 1 To 1): v(1, 1) = t
Application.EnableEvents = False
For i = 1 To UBound(v)
For j = 1 To UBound(v, 2)
If Len(v(i, j)) = 0 Then
With Target(i, j)
Select Case .Address(0, 0)
Case "A1": .Formula = "=""Excel"""
Case "A2": .Formula = "=""Hero"""
End Select
End With
End If
Next
Next
Application.EnableEvents = True
End Sub

当然,请使用您的公式和范围而不是我的。

更新

上面的效果很好,但这更快/更好......
Private Sub Worksheet_Change(ByVal Target As Range)
Dim i&, v
DoEvents
ReDim v(1 To 3, 1 To 2)
v(1, 1) = "A1": v(1, 2) = "=""This"""
v(2, 1) = "A2": v(2, 2) = "=""Works"""
v(3, 1) = "A2": v(3, 2) = "=""Great!"""
Application.EnableEvents = False
For i = 1 To UBound(v)
With Range(v(i, 1))
If Not Intersect(Target, .Cells) Is Nothing Then
If Len(.Value2) = 0 Then
.Formula = v(i, 2)
End If
End If
End With
Next
Application.EnableEvents = True
End Sub

上述两种方法都适用于单单元格删除,也适用于清除和删除大范围,包括整列和整行,第二种方法在所有这些情况下都特别快。

关于excel - VBA Worksheet_Change 仅适用于一个单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60717285/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com