dynamic单元格范围VBA

我有一个macros,我正在努力。 它检测一个单元格是否具有NA的值,如果它运行了一段代码。

问题:到目前为止,我只能在一个单元上运行它。 我正在尝试将下面的单元格应用于我的macros。

(D)(D)(20,24,25,27,28,30,31,32,33,34,35,37,38,40,42,43,44,54,55,56,58,59,61 ,62,63,64,65)

(第23,24,25,27,28,30,31,32,33,34,35,37,38,40,42,43,44,54,55,56,58,59,61号) ,62,63,64,65)

Private Sub Worksheet_Change(ByVal Target As Excel.Range) Dim sCellVal As String sCellVal = Range("D20") If sCellVal Like "*NA*" Then Range("D20") = "Not applicable" & " " & Environ("Username") & " " & Format(Now, "yyyy-MM-dd hh:mm:ss") End If End Sub 

有一个替代方法。 您可以按照以下步骤操作:

  1. 使用IFERROR(cellReferenceHere; functionName())
  2. 把它作为公共函数写在VBA上。

它总是会在#N / A发生时触发

例如:手机:

 =IFERROR(0/0;doSomething()) 

VBA:

 Public Function doSomething() doSomething = "Done" End Function 

我没有看到在这个范围内使用的行的任何明显的逻辑,所以我们将在一个Case开关中对行号进行硬编码,然后检查Target.Row

 Private Sub Worksheet_Change(ByVal Target As Excel.Range) '// Check if the target row number is in our array: Select Case Target.Row Case 20, 24, 25, 27, 28, 30, 31, 32, 33, 34, 35, 37, 38, 40, 42, 43, 44, 54, 55, 56, 58, 59, 61, 62, 63, 64, 65 ' Do Something If Cstr(Target.Value) Like "*NA*" Then Target.Value = "Not applicable" & " " & Environ("Username") & " " & Format(Now, "yyyy-MM-dd hh:mm:ss") End If Case Else ' Do nothing Exit Sub End Select End Sub 

注意:如果您正在查找错误值,而不是与Like运算符进行string比较,请检查真正的错误等价性:

 If Target.Value = CvErr(2042) Then Target.Value = "Not applicable" & " " & Environ("Username") & " " & Format(Now, "yyyy-MM-dd hh:mm:ss") End If 

似乎没有一个可辨别的范围模式,所以我已经硬编码到一个数组。 这就是你所需要的,但是我将把它留给你创build列E的数组:

 Sub Worksheet_Change() Dim ws_data As Worksheet Dim arr_Range(0 To 9) As String Dim i as Integer Set ws_data = ThisWorkbook.Sheets("Data") 'change to your sheet name arr_Range(0) = "D20" arr_Range(1) = "D24:D25" arr_Range(2) = "D27:D28" arr_Range(3) = "D30:D35" arr_Range(4) = "D37:D38" arr_Range(5) = "D40" arr_Range(6) = "D42:D44" arr_Range(7) = "D54:D56" arr_Range(8) = "D58:D59" arr_Range(9) = "D61:D65" 'Loop through array For i = LBound(arr_Range) To UBound(arr_Range) For Each Cell In ws_data.Range(arr_Range(i)) 'check each cell in the current range string in the array If Cell.Value Like "*NA*" Then Cell.Value = "Not applicable" & " " & Environ("Username") & " " & Format(Now, "yyyy-MM-dd hh:mm:ss") Else: End If Next Cell Next i End Sub 

在这里,我只是做了一个数组,并在数组上做了一个快速循环来查看所有的范围并testing条件。

 Sub test() Dim D As Variant Dim rng1 As Range Dim rng2 As Range Dim x As Integer D = Array(20, 24, 25, 27, 28, 30, 31, 32, 33, 34, 35, 37, 38, 40, 42, 43, 44, 54, 55, 56, 58, 59, 61, 62, 63, 64, 65) For x = LBound(D) To UBound(D) Set rng1 = Cells(D(x), 4) Set rng2 = Cells(D(x), 5) If rng1 Like "*NA*" Then rng1 = "Not applicable" & " " & Environ("Username") & " " & Format(Now, "yyyy-MM-dd hh:mm:ss") End If If rng2 like "*NA*" then rng2 = "Not applicable" & " " & Environ("Username") & " " & Format(Now, "yyyy-MM-dd hh:mm:ss") End if Next x End Sub