VBA if 语句返回错误"object variable or with block variable not set"



有人能帮助我理解为什么我的If语句返回此错误,以及如何更好地执行预期任务吗?

这个Sub的目标是将公司记录/销售额从工作表src复制到工作表des,但如果一个公司有多个记录,我希望对销售额求和,并且在des上只有一个记录。它首先从src中获取一个公司名称,然后检查它是否存在于des中。

Sub populate_sales()
slr = src.Range("A" & Rows.Count).End(xlUp).row
For r = 2 To slr
dlr = des.Range("A" & Rows.Count).End(xlUp).row
c_name = src.Range("M" & r).Value
Dim d_names As Range
Set d_names = des.Range("A1", des.Range("A" & dlr + 1))
If d_names.Find(c_name) = False Then
' start the summing + writing process
Else
' skip to next next record
End If
Next
End Sub

对于记录,尽管这里只定义了d_names,但所有变量都是定义的,我只是为多个子系统使用的变量全局定义。事实上,只要c_name已经存在于d_names范围内,If语句就会起作用,并跳到下一个公司。然而,如果该公司不存在于CCD_ 12中,则返回突出显示CCD_ 13的错误。

我们非常感谢社区提供的任何帮助。

这将帮助您理解Find Method

Sub populate_sales()
Dim rngFound As Range, rngSearchIn As Range
Dim strSearchFor As String
With ThisWorkbook.Worksheets("Sheet1")
'Set the value you want to search for
strSearchFor = "Test"
'Set the range you want to search in
Set rngSearchIn = .Range("A1:A5")
Set rngFound = rngSearchIn.Find(strSearchFor, LookIn:=xlValues, Lookat:=xlWhole)
If rngFound Is Nothing Then
MsgBox "Values not found."
Else
MsgBox "Values found."
End If
End With
End Sub

相关内容

最新更新