两个Sub程序,为什么这个函数在运行两次之后会导致一个对象variables错误
我有两个Sub程序,这两个都是非常长的时间来粘贴在这里的整体,但我已经缩小了代码块下面的函数和调用程序,这是导致错误。
我能够运行Sub 1和然后Sub 2没有任何问题,然后当我尝试重新运行Sub 1时,我收到一个object variable not set
错误在这一行是在Sub 1:
cName = "Current Price" cG = ActiveSheet.Rows.Find(What:=UCase(cName), Lookat:=xlWhole, SearchDirection:=xlNext).Column
“当前价格”是拼写正确的,并且是作为parameter passing的每个工作表上的一个列标题,再次Sub 1首次运行良好,这可能是公开声明的问题吗? 该错误归因于下面的IsInArray
函数
Sub 1
Sub Example(ws_string As String) Sheets(ws_string).Activate LR = Range("a1000").End(xlUp).Row LC = Range("zz1").End(xlToLeft).Column cName = "Fund ID" cA = ActiveSheet.Rows.Find(What:=UCase(cName), Lookat:=xlWhole, SearchDirection:=xlNext).Column cName = "BBH ID" cB = ActiveSheet.Rows.Find(What:=UCase(cName), Lookat:=xlWhole, SearchDirection:=xlNext).Column cName = "Description" cC = ActiveSheet.Rows.Find(What:=UCase(cName), LookAt:=xlWhole, SearchDirection:=xlNext).Column cName = "Security Type" cD = ActiveSheet.Rows.Find(What:=UCase(cName), Lookat:=xlWhole, SearchDirection:=xlNext).Column cName = "Price Date" cF = ActiveSheet.Rows.Find(What:=UCase(cName), Lookat:=xlWhole, SearchDirection:=xlNext).Column cName = "Current Price" cG = ActiveSheet.Rows.Find(What:=UCase(cName), Lookat:=xlWhole, SearchDirection:=xlNext).Column cName = "Prior Price" cH = ActiveSheet.Rows.Find(What:=UCase(cName), Lookat:=xlWhole, SearchDirection:=xlNext).Column
Sub 2
Set aSelection = Range("C2:C1500") Set aSelect_Recon = Sheets("Recon").Range("L2:C1500") For Each cell In aSelection If IsInRange(cell.Value, aSelect_Recon) Then cell.Interior.ColorIndex = 10 End If Next cell Function IsInRange(stringToBeFound As String, ByVal rng As Range) As Boolean Dim r As Range Set r = rng.Find(What:=stringToBeFound, _ MatchCase:=True, _ LookIn:=xlValues, _ Lookat:=xlPart) 'partial match to have the same behaviour as the filter version If Not r Is Nothing Then IsInRange = True End Function
编辑更新进一步,我打电话给Sub 1三次传递不同的工作表,如下所示:
Example "ETF" Example "MAV" Example "Main"
但如果我注释掉ETF和MAV呼叫,Main程序调用就可以正常工作。
你需要Set
查找值,不能设置它们
Set rngTest = ActiveSheet.Rows.Find(What:=UCase(cName), Lookat:=xlWhole, SearchDirection:=xlNext) if Not rngTest is Nothing then cA= rngTest.Column end if
build议:开始使用Option Explicit
,这将有助于避免这些错误。
我认为这是问题: Find
方法的选项被保存。 (它们与Excel中的查找窗口相同)。 运行IsInRange
函数后, IsInRange
选项设置为True
。 在你的例子中,您正在寻找UCase(cName)
所以当您在IsInRange
之后运行它时,您正在查找"CURRENT PRICE"
,并在IsInRange
Object not set
IsInRange
Object not set
错误时引发此错误。
解决方法是在Example
子项中设置MatchCase:=False
。
编辑:Follow cyboashu的有关Option Explicit
的build议,并检查对象,即使这现在解决了问题!
(PS:我在IsInRange
函数中包含了MatchCase:=True
选项以重现与Filter
函数相同的结果。)
如果它解决了你的问题,也请接受一个答案 (你甚至可以放弃)。
如果它不能解决您的问题,请写下评论并解释原因。