Excel VBA 工作表_更改值范围

问题描述

我在使用 VBA 时遇到问题,我需要使用工作表更改事件将单元格值从 AI28 提取到 AI30,并将它们移到 V28 到 V30。这是我目前所做的

Private Sub Worksheet_Change(ByVal Target As Range)

If IsNumeric(Target) And Not (Target = "") Then
  If Target.Address = Range("AI28:AI30").Address Then
   Range("V28:V30").Value = Range("AH28:AH30").Value
   
   Else
      If Target.Cells.Value <> Empty Then Exit Sub
   Exit Sub
   
   End If

End If
    
End Sub

它仅适用于一个范围,例如 AI28 和 V28,那么我错过了什么?循环还是什么?

解决方法

使用循环和Intersect

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim rng As Range
    Set rng = Intersect(Target,Me.Range("AI28:AI30"))

    If rng Is Nothing Then Exit Sub

    On Error GoTo SafeExit
    Application.EnableEvents = False

    Dim cell As Range
    For Each cell In rng
        If IsNumeric(cell.Value) And Not IsEmpty(cell.Value) Then
           Me.Range("V" & cell.Row).Value = cell.Value
        End If
    Next

SafeExit:
    Application.EnableEvents = True

End Sub

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...