下面的代码中的find方法存在问题。
c = Cells.find(wValue).Address
我总是会遇到运行时错误91:对象变量或未设置块变量。 当我在不带循环的试用代码中对其进行尝试时,它可以完美地工作,但是我无法真正弄清楚,为了使其正常工作,我到底需要更改什么。
您对此有何建议?
Sub find()
Dim cRange As Range, rngQty As Range, z As Range
Dim Date1 As Integer
Dim c As String
With Application
.ScreenUpdating = False
.EnableEvents = False
End With
Set wkbZ = Workbooks("Order History.xlsm")
Set wkbY = Workbooks("Forecast Form.xlsm")
For Each z In wkbZ.Sheets("2015").Range(Range("A2"), Range("A2").End(xlDown))
Set rngQty = z.Offset(, 3)
Date1 = Month(z.Offset(, 4))
wValue = z.Value
wkbY.Activate
c = Cells.find(wValue).Address
Set cRange = Range(c)
cRange.Select
If Date1 = 1 Then
Set rngPaste1 = Selection.Offset(, 3)
End If
If Date1 = 2 Then
Set rngPaste = cRange.Offset(, 4)
End If
If Date1 = 3 Then
Set rngPaste = cRange.Offset(, 5)
End If
If Date1 = 4 Then
Set rngPaste = cRange.Offset(, 6)
End If
If Date1 = 5 Then
Set rngPaste = cRange.Offset(, 7)
End If
If Date1 = 6 Then
Set rngPaste = cRange.Offset(, 8)
End If
If Date1 = 7 Then
Set rngPaste = cRange.Offset(, 9)
End If
If Date1 = 8 Then
Set rngPaste = cRange.Offset(, 10)
End If
If Date1 = 9 Then
Set rngPaste = cRange.Offset(, 11)
End If
If Date1 = 10 Then
Set rngPaste = cRange.Offset(, 12)
End If
If Date1 = 11 Then
Set rngPaste = cRange.Offset(, 13)
End If
If Date1 = 12 Then
Set rngPaste = cRangec.Offset(, 14)
End If
rngPaste.Value = (rngPaste.Value) + (rngQty.Value)
wkbZ.Activate
Next
With Application
.ScreenUpdating = True
.EnableEvents = True
End With
End Sub
答案 0 :(得分:0)
未经测试,但应该靠近...
Sub find()
Dim cRange As Range, rngQty As Range, z As Range
Dim Date1 As Integer
Dim rngSrch As Range
Dim wkbZ As Workbook
Dim wkbY As Workbook
Set wkbZ = Workbooks("Order History.xlsm")
Set wkbY = Workbooks("Forecast Form.xlsm")
'fully-qualify all Range calls with a worksheet object
With wkbZ.Sheets("2015")
Set rngSrch = .Range(.Range("A2"), .Range("A2").End(xlDown))
End With
For Each z In rngSrch.Cells
Set rngQty = z.Offset(0, 3)
Date1 = Month(z.Offset(0, 4))
'better to specify whether looking at full content or part..
'also not clear which sheet you're searching?
'notice no select/activate needed...
Set cRange = wkbY.Sheets(1).Cells.find(what:=z.Value, lookat:=xlWhole)
If Not cRange Is Nothing Then
With cRange.Offset(0, Date1 + 2)
.Value = .Value + rngQty.Value
End With
End If
Next
End Sub