VBA 错误 : Object variable or with variable not set

标签 vba excel

<分区>

我在 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

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

谢谢, 阿美

最佳答案

问题是 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)

关于VBA 错误 : Object variable or with variable not set,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11917841/

相关文章:

Excel 使用宏复制公式

VB6 Excel.Application对象 "Permission Denied"

vba - Excel VBA - 从多个工作簿中的数据创建多个文件

excel - 如何在excel VBA中读取目录中的某些文件

excel - 查找值 - #N/A 结果

javascript - 如何将 Excel 数据复制到 HTML 表格?

excel - 如何将 Cells().Select 命令中的单元格的值设置为其中包含公式的单元格的值?

Excel - 以单元格值作为参数对 SSAS 多维数据集进行 MDX 查询

vba - 如何在Excel VBA中选择全范围

excel - 计算 MS Excel 中特定数据类型的单元格数量