【发布时间】:2020-12-15 01:23:19
【问题描述】:
我为“输入”中的数字条目(C 列)创建了一个数组,并将使用它在“目标”的 G 列中进行搜索。
如果有匹配项,请将“Destination”的行值替换为与“Input”中相应列的数组相关联的值。例如,我将使用“输入”中的数字 13579 并在“目标”中的 G 列下搜索,当匹配时,使用与“输入”中的 13579 相关联的日期(A 列)和人员(B 列)值并替换单元格相同列的“目的地”中的值(B 列代表日期,D 列代表人物)。
我是 VBA 新手,尝试了自己的逻辑并得到“需要对象”错误。我标记了“需要帮助”的部分(接近代码末尾)。谢谢!
Sub ReplaceValue()
' Use entries in Input worksheet as filter criteria for Summary worksheet, copy data to
' Destination worksheet and replace cell value based on Input array.
Application.ScreenUpdating = False
Dim srcWS As Worksheet, inputWS As Worksheet, desWS As Worksheet
Dim cell As Variant, c As Variant
Set srcWS = ThisWorkbook.Sheets("Summary") ' Thousands of rows
Set inputWS = ThisWorkbook.Sheets("Input")
Set desWS = ThisWorkbook.Sheets("Destination")
srcWS.AutoFilterMode = False
' Declare an array to hold filtered criteria
Dim inputList() As String
' Declare a counter for inputList array
Dim n As Integer
n = Application.WorksheetFunction.CountA(inputWS.Range("C:C")) - 2 ' Column has header
ReDim inputList(n) As String
Dim i As Integer
For i = 0 To n
inputList(i) = inputWS.Range("C" & i + 2)
Next i
' Use Input array to filter the Summary worksheet and copy data to the Destination worksheet
With srcWS.UsedRange
.AutoFilter 7, inputList(), xlFilterValues
.Offset(1).Resize(.Rows.Count - 1).Copy desWS.Range("A" & Rows.Count).End(xlUp).Offset(1, 0)
'.AutoFilter
End With
' Loop through Input array
For Each cell In inputList
If IsError(Application.Match(cell, desWS.Range("G:G"), 0)) Then
MsgBox (cell & " Not Found")
Else
' This is where help is needed. Got "Object required" error.
For Each c In desWS.Range("G:G")
desWS.Cells(c.Row, 2).Value2 = inputWS.Cells(cell.Row, 1).Value2 ' Copied Date
desWS.Cells(c.Row, 4).Value2 = inputWS.Cells(cell.Row, 2).Value2 ' Copied Person
Next c
End If
Next cell
srcWS.AutoFilterMode = False
' Display to user the last row in the Destination worksheet
desWS.Activate
Range("C" & Rows.Count).End(xlUp).Select
Application.ScreenUpdating = True
End Sub
【问题讨论】:
-
您是否查看过任何变量是否为空?尝试使用调试器
-
cell是数组InputList中的一个元素,因此它没有 Row 属性。那是范围的属性。 -
@Nirostar 我还不熟悉调试器,需要自己学习。我相信所有变量都被声明并赋值。
-
@SJR 感谢您提供有关元素单元的信息。如何修改以做我想做的事?