【发布时间】:2017-03-16 17:54:12
【问题描述】:
我有两个主要功能,第一个是search_bank。它逐个单元格地搜索 Credits、Type 和存储列,并确定我们是否匹配。如果匹配,它返回 True 并且作为副作用会更改匹配单元格的颜色。
我用来测试第一个函数的第二个sub。 我遇到的问题是我收到运行时错误“424”:需要对象,但没有指出问题出在哪里。
这是第一个函数:
Function search_bank(Store As String, amount As Double, Amex As Boolean) As Boolean
Dim m_store As Range
Dim m_type As Range
Dim Credit_Amt_Col As Range
Set m_store = bank_sheet.Range("1:1").Find("M_STORE")
Set m_type = bank_sheet.Range("1:1").Find("M_TYPE")
Set Credit_Amt_Col = bank_sheet.Range("1:1").Find("Credit Amt")
search_bank = False
Dim i As Long
For i = 1 To 9000
If Not search_bank Then
Dim store_cell As Range
Dim type_cell As Range
Dim credit_cell As Range
Set store_cell = Worksheets(2).Cells(i, m_store.Column)
Set type_cell = Worksheets(2).Cells(i, m_type.Column)
Set credit_cell = Worksheets(2).Cells(i, Credit_Amt_Col.Column)
If InStr(UCase(store_cell.Value), UCase(Store)) > 0 And credit_cell.Value = amount Then
If store_cell.Interior.ColorIndex <> 46 Then
If Amex And InStr(UCase(type_cell.Value), UCase("amex deposit")) Then
store_cell.Interior.ColorIndex = 46
search_bank = True
End If
If Not Amex And InStr(UCase(type_cell.Value), UCase("Credit Card Deposit")) Then
store_cell.Interior.ColorIndex = 46
search_bank = True
End If
End If
End If
End If
Next i
End Function
这是测试人员:
Sub Tester()
Dim x As Boolean
x = search_bank("ctc", 38.4, True)
Debug.Print (x)
End Sub
我尝试在测试仪上使用“设置”:
Sub Tester()
Dim x As Boolean
Set x = search_bank("ctc", 38.4, True)
Debug.Print (x)
End Sub
甚至在将变量传递给测试器之前声明变量(我不太习惯 VBA,但有一段时间我认为它太古老了,需要在传递之前声明一些东西)
Sub Tester()
Dim x As Boolean
Dim store As String
Dim Amount As Double
Dim amex As Boolean
store = "ctc"
Amount = 38.4
amex = True
x = search_bank(store, Amount, amex)
Debug.Print (x)
End Sub
【问题讨论】:
-
当您收到运行时错误时,选择“调试”选项并使用 F8 单步执行代码,直到您看到错误所在的行。
-
您在何处/何时/如何声明
bank_sheet? -
另外,确保您的三个
Find方法的结果返回有效对象。如果在第 1 行中找不到这些值,则它们将返回Nothing,这将在您的代码中稍后引发此错误。 -
Range.Find可以返回Nothing。您必须测试返回值。 -
@RyanFrancis FWIW 你确实有一个免费的全局工作表对象。查看 Project Explorer 工具窗口;工作表节点显示为
Sheet1 (Sheet1)- 那是CodeName (WorksheetName),其中CodeName是您免费获得的全局范围Worksheet对象变量。您可以在 properties 工具窗口 (F4) 中通过更改(Name)属性来控制其名称。