Excel VBA激活Range类的方法失败
我有一个代码,我用在一个不同的macros,并认为现在不工作,我不断得到运行时错误1004行与激活:
Sub initialize() dim MonthName as string dim MainWB as workbook dim VisualWS as worksheet MonthName = cells (1,1).value Set MainWB = ThisWorkbook Set VisualWS = MainWB.Worksheets("Visual") With VisualWS .Range("L1:W1").Find(MonthName, , xlValues, xlWhole).Activate End With MonthCol = ActiveCell.Column End Sub
根据Range.Find上的文档 ,“如果找不到匹配,方法返回Nothing
”。
最有可能的是,你的.Range()。Find()方法没有find任何匹配,因此返回Nothing
,它没有一个函数Activate
。
试试这个:
Dim findResult As Range Set findResult = .Range("L1:W1").Find(MonthName, , xlValues, xlWhole) If findResult <> Nothing then findResult.Activate
Find
可能会返回Nothing
,所以我宁愿写:
With VisualWS set target = .Range("L1:W1").Find(MonthName, , xlValues, xlWhole) End With If target is Nothing Then DoSomething else MonthCol = target.Cells(1,1).Column End if
(另)