2012-08-11 118 views
1

在VBA運行該子程序時,我收到一個奇怪的錯誤:VBA錯誤:對象變量或與變量未設置

Sub NameColumns() 
' name key columns for later reference in formulas 
Dim startdatecol As Integer 

' name start date column 
startdatecol = ActiveSheet.Cells.Find(What:="Start Date", after:=[a1], LookIn:=xlValues, _ 
LookAt:=xlPart, SearchOrder:=xlByColumns, SearchDirection:=xlNext, _ 
MatchCase:=False, SearchFormat:=False).Column 
End Sub 

Run time error '91': Object variable or With variable not set

我如何能解決這個子程序錯誤任何想法?爲什麼它正在發生?

感謝, AME

+0

我這個苦苦掙扎前幾天,答案是改變Excel中單元格的格式。由於我搜索的Excel單元格是數字和Find()方法搜索字符串 – 2018-03-01 14:09:04

回答

3

的問題是,Find沒有找到小區。

你會發現(雙關語意),以下爲真:

MsgBox ActiveSheet.Cells.Find(What:="Start Date", after:=[a1], LookIn:=xlValues, _ 
LookAt:=xlPart, SearchOrder:=xlByColumns, SearchDirection:=xlNext, _ 
MatchCase:=False, SearchFormat:=False) Is Nothing 

你應該做的第一件事就是解決您的搜索,這樣它找到你要找的細胞。

編輯:

可能發生變化,更好地說明這個問題是這樣的:

Dim found as Range 
Dim startDateCol as Integer 

Set found = ActiveSheet.Cells.Find(What:="Start Date", after:=[a1], LookIn:=xlValues, _ 
LookAt:=xlPart, SearchOrder:=xlByColumns, SearchDirection:=xlNext, _ 
MatchCase:=False, SearchFormat:=False) 

If Not found Is Nothing Then startDateCol = found.Column 

MsgBox startDateCol 'This will be zero if the "Start Date" cell wasn't found. 

編輯迴應評論:

'This should find the exact text "Start Date" (case sensitive) in the header row. 
'A cell containing, for example "The Start Date" will not be matched. 
Set found = ActiveSheet.Range("1:1").Find("Start Date", LookIn:=xlValues, _ 
              LookAt:=xlWhole, MatchCase:=True) 
+0

如果這些都沒有意義,只需詢問! :) – mkingston 2012-08-11 21:58:44

+0

謝謝,你是正確的活動單元格低於標題行,所以該子程序無法找到標題爲'開始日期'的標題。這引發了另一個問題,如何限制子程序中的搜索功能,以便它只搜索標題行並僅返回精確匹配? – AME 2012-08-11 21:59:20

+0

我編輯了我的答案,以顯示如何在第一行中找到確切的文本「開始日期」。根據您告訴我的情況,我不確定這會是您的問題,但請放手。 – mkingston 2012-08-11 22:05:07

相關問題