Find()导致Object变量或With Block变量未设置



感谢阅读我的文章。我是Excel VBA的新手,在调试对Find()的调用时遇到了麻烦。我已经浏览了这个网站和其他网站上的几篇帖子,但到目前为止,我尝试的每一个修复都没有成功。

我正在编写代码来处理财务报告中的元素。每个报告包含一个或多个多行&多列单元格块,其中包含描述项目的详细信息。每个块的大小并不一致,但每个块总是以"客户端名称"从左上角开始。因此,我想遍历这些块,键入文本,然后提取所需的元素。

这里还没有while循环,因为我在设置第一个条件时遇到了错误。

运行时错误"91":对象变量或With块变量未设置

以下是Sub中的代码部分,错误出现在分配游标项目的最后一行:

' store the next report to process
Dim nextReport As String
Dim sourceSheetName As String
Dim sheetSource As Worksheet
nextReport = rptMedia
' copy the worksheet into rptBurn and get that worksheet's name
sourceSheetName = GetSheet(nextReport)
Set sheetSource = Workbooks(rptBurn).Worksheets(sourceSheetName)
sheetSource.Cells.EntireRow.Hidden = False
sheetSource.Cells.EntireColumn.Hidden = False
Workbooks(rptBurn).Activate
' process the sheetSource into sheetCurrent
' set constants
Const constCursorKey As String = "Client Name"
Const constClientColumn As String = "B"
Const constClientNameOffset As Integer = 2
Const constProjectLeft As Integer = 2
Const constProjectRight As Integer = 52
' get range in Client Name column of project entries
Dim cursorStart As Long
Dim cursorEnd As Long
Dim cursorProject As Range
Dim rangeProject As Range
Dim rangeSearch As Range
cursorStart = sheetSource.Columns(2).Find(constCursorKey).Row + constClientNameOffset
' find the last project entry in the sheet 
cursorEnd = sheetSource.Range("B" & Rows.Count).End(xlUp).Row
Set rangeSearch = sheetSource.Range(Cells(cursorStart + 1, constProjectLeft), _
                        Cells(cursorEnd, constProjectLeft))
cursorProject = rangeSearch.Find(What:=constCursorKey, LookIn:=xlValues, LookAt:=xlPart, _
                    SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False, _
                    SearchFormat:=False)

目前这是非常草率的,因为在迭代报告时,部分将被移到自己的Sub调用中(因此nextReport在这里被硬编码为特定的报告名称)。各种常量是报表的固定参数。未列出的值(如"rptBurn")是全局值。GetSheet函数运行良好,但如果您想查看它:

Private Function GetSheet(rpt As String) As String
   Workbooks.Open rootPath + rpt
   ActiveSheet.Copy after:=Workbooks(rptBurn).Sheets(Workbooks(rptBurn).Sheets.Count)
   GetSheet = ActiveSheet.Name
   Workbooks(rpt).Close
End Function

我试过几种不同的方法。本地人似乎都对这个错误充满希望。我根据另一篇帖子将隐藏属性设置为False。我试着将呼叫简化为基本呼叫,并使用With,如下所示:

    Set rangeSearch = Sheets(3).Range("B:B")
    rangeSearch.Select
    With rangeSearch
      cursorProject = .Find("Client Name")
    End With

但我总是在cursorProject上出错。在我测试的工作表中肯定有很多"客户名称"条目。我输入Select(选择)以验证我是否获得了正确的范围;奇怪的是,我发现"B:AX"在简单版本中被突出显示(AX是报告中最右边使用的列),但我期望在原始版本中进行选择。无论在任何一个选择中是否有"客户端名称"实例,我都可以选择B4并查看"客户端姓名"。

我做错了什么?

Cursorproject是一个对象变量(范围)。你不能简单地给一个对象变量赋值,你必须设置它

dim strSomeTextVarible as string
dim rngSomeCellsObjectVariable as range
strSomeTextVarible = "abc"
set rngSomeCellsObjectVariable = range("a1:c3")

最新更新