3

在 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

运行时错误“91”:对象变量或未设置变量

关于如何修复此子程序错误的任何想法?为什么会发生?

谢谢, AME

4

1 回答 1

5

问题是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)
于 2012-08-11T21:55:28.537 回答