【问题标题】:Find method with no match error [duplicate]查找没有匹配错误的方法[重复]
【发布时间】:2016-11-02 18:02:37
【问题描述】:

我不断收到 “运行时错误 '91':未设置对象变量或块变量。我知道问题是 find 方法没有找到匹配项,但我可以”似乎找不到解决问题的方法。我尝试了 If Not xxx Is Nothing...但我又遇到了另一个错误。

Sub SetUpFormulas50450()

Dim cnt1 As Long
Dim i As Long
Dim lnRow As Long
Dim lnCol As Long
Dim lnCol1 As Long
Dim lnCol4 As Long
Dim lnRow1 As Long
Dim tempA As Long
Dim tempB As Long
Dim a As Long
Dim LR As Long

Set Sh1 = ThisWorkbook.Worksheets("Pivot")
Sh1.Select

lnRow = 5
lnCol = 2

cnt1 = Sh1.Cells(Rows.Count, "A").End(xlUp).Row

'Sh1.Cells(1, 10) = cnt1

lnCol1 = Sheet1.Cells(lnRow, 1).EntireRow.Find(What:="Grand Total", LookIn:=xlValues, LookAt:=xlPart, SearchOrder:=xlByColumns, SearchDirection:=xlNext, MatchCase:=False).Column
'Sh1.Cells(1, 11) = lnCol1

Sh1.Cells(cnt1, (lnCol1 + 2)).Formula = "=SUM(" & Range(Cells(6, (lnCol1 + 2)), Cells((cnt1 - 1), (lnCol1 + 2))).Address(False, False) & ")"

'Calculate Frt Pct of Sales
For i = 6 To cnt1
    tempA = Sh1.Cells(i, lnCol1).Value
    tempB = Sh1.Cells(i, (lnCol1 + 2)).Value
    If Sh1.Cells(i, (lnCol1 + 2)).Value = 0 Then Sh1.Cells(i, (lnCol1 + 3)).Value = 0 Else Sh1.Cells(i, (lnCol1 + 3)).Value = tempA / tempB
Next i

'Calculate Frt Pd in Fut Mos
For a = 2 To (lnCol1 - 2)
    For i = 6 To (cnt1 - 2)
        lnCol4 = Sheet1.Cells(lnRow, 1).EntireRow.Find(What:=Sh1.Cells(i, 1).Value, LookIn:=xlValues, LookAt:=xlPart, SearchOrder:=xlByColumns, SearchDirection:=xlNext, MatchCase:=False).Column
        Sh1.Cells(i, (lnCol1 + 4)).Formula = "=SUM(" & Range(Cells(i, (lnCol4 + 1)), Cells(i, (lnCol1 - 1))).Address(False, False) & ")"
    Next i
Next a
End Sub

我遇到了问题:

lnCol4 = Sheet1.Cells(lnRow, 1).EntireRow.Find(What:=Sh1.Cells(i, 1).Value, LookIn:=xlValues, LookAt:=xlPart, SearchOrder:=xlByColumns, SearchDirection:=xlNext, MatchCase:=False).Column

【问题讨论】:

  • 您需要在调用Find 后测试Nothing。这个确切的问题每天都会被认真地问到这里。

标签: vba excel find match


【解决方案1】:
Dim f As Range '<-- declare a range to collect the result of 'Find()' method
For a = 2 To (lnCol1 - 2)
    For i = 6 To (cnt1 - 2)
        Set f = Sheet1.Cells(lnRow, 1).EntireRow.Find(What:=Sh1.Cells(i, 1).Value, LookIn:=xlValues, LookAt:=xlPart, SearchOrder:=xlByColumns, SearchDirection:=xlNext, MatchCase:=False) '<-- try setting f to the 'Find()' method result
        If Not f Is Nothing Then '<--| check for f to be a "real" range
            lnCol4 = f.Column
            Sh1.Cells(i, (lnCol1 + 4)).Formula = "=SUM(" & Range(Cells(i, (lnCol4 + 1)), Cells(i, (lnCol1 - 1))).Address(False, False) & ")"
        End If
    Next i
Next a

【讨论】:

  • 谢谢大家!我正在尝试提出的所有其他问题的建议。我的问题是当我在测试什么时我没有在行尾删除 .column 。一旦我这样做了,然后设置 If 语句就像一个魅力!
  • 不客气。然后,您可能想将我的答案标记为已接受。谢谢
猜你喜欢
  • 1970-01-01
  • 2016-07-07
  • 2020-03-27
  • 2020-07-02
  • 2016-10-03
  • 1970-01-01
  • 2017-05-05
  • 1970-01-01
  • 2023-03-23
相关资源
最近更新 更多