在 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 Code Online (Sandbox Code Playgroud)
运行时错误“91”:未设置对象变量或 With 变量
关于如何修复此子例程错误有什么想法吗?为什么会发生这种情况?
谢谢,阿梅
问题是Find没有找到单元格。
你会发现(双关语)以下内容是正确的:
MsgBox ActiveSheet.Cells.Find(What:="Start Date", after:=[a1], LookIn:=xlValues, _
LookAt:=xlPart, SearchOrder:=xlByColumns, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False) Is Nothing
Run Code Online (Sandbox Code Playgroud)
您应该做的第一件事是修复您的搜索,以便找到您要查找的单元格。
编辑:
也许更能说明问题的改变是:
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.
Run Code Online (Sandbox Code Playgroud)
编辑以回复评论:
'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)
Run Code Online (Sandbox Code Playgroud)