excel - 如果在宏开始处未显示工作表,则 .find() 什么都不是
问题描述
我的问题对我来说很奇怪。我正在搜索和阅读其他 VBA 问题,在我看来,这些问题与我的问题更加平等。我不知道。
用例: 宏应激活/选择活动工作簿中的工作表。然后在该活动工作表中找到日期/字符串。如果找到它会将范围保存到变量中。如果变量什么都没有,那么宏应该停止。
问题:如果宏启动时未选择/激活工作表,则 .find() 不起作用。每次我得到一个“无”的回报。如果通过宏启动(显示在我的显示器上)选择/激活了工作表,那么它可以工作。
我也在另一台电脑上检查了这个问题。但它也发生在那里......
Dim rngFirst As Range
Dim rngNext As Range
Dim rngArea As Range
Set rngArea = Range("A:Z")
Dim defaultValue As Date, insertedDate As Date
defaultValue = Format(Date, "dd.mm.yyyy")
insertedDate = Application.InputBox(message, title, Format(defaultValue, "dd.mm.yyyy"), Type:=1)
ActiveWorkbook.Sheets("mySheet").Activate
Do
If rngFirst Is Nothing Then
Set rngFirst = rngArea.Find(What:=insertedDate, After:=rngArea(1)) 'the problem start with this code line. What I got back is "Nothing"
Set rngNext = rngFirst
If rngNext Is Nothing Then
MsgBox "There was a problem with finding the meeting date. Please check!" + Chr(10) + "The Macro will end here."
Exit Sub
End If
Else
'Do something with what was found
'find the next entry in the sheet
Set rngNext = rngArea.Find(What:=insertedDate, After:=rngNext)
If rngNext.Address = rngFirst.Address Then Exit Do
End If
Loop
注意:不幸的是,我的工作 PC 上没有管理员……但我认为这并没有什么不同。
解决方案
解决了。这是一种错误的思维方式......我的问题下的评论解释了解决方案。
这是工作代码:
Dim rngFirst As Range
Dim rngNext As Range
Dim rngArea As Range
Set rngArea = Sheets("mySheet").Range("A:Z") 'added solution here
Dim defaultValue As Date, insertedDate As Date
defaultValue = Format(Date, "dd.mm.yyyy")
insertedDate = Application.InputBox(message, title, Format(defaultValue, "dd.mm.yyyy"), Type:=1)
Do
If rngFirst Is Nothing Then
Set rngFirst = rngArea.Find(What:=insertedDate, After:=rngArea(1)) 'the problem start with this code line. What I got back is "Nothing"
Set rngNext = rngFirst
If rngNext Is Nothing Then
MsgBox "There was a problem with finding the meeting date. Please check!" + Chr(10) + "The Macro will end here."
Exit Sub
End If
Else
'Do something with what was found
'find the next entry in the sheet
Set rngNext = rngArea.Find(What:=insertedDate, After:=rngNext)
If rngNext.Address = rngFirst.Address Then Exit Do
End If
Loop
推荐阅读
- ngrx-effects - ngrx 效果中的错误处理
- javascript - Express.js 应用程序在本地运行良好,但在 Heroku 上部署时无法运行
- linux - 评估变量 - 输出 json 文件内容
- php - 将mysql查询的结果用于新查询
- excel - Excel:如何通过两列查找返回唯一列表数组
- sql-server - 使用 Attunity 连接器进行增量加载
- c++ - 有没有一种简单的方法可以从 C++ 中的路径获取文件名?
- objective-c - Objective C - 访问 typedef 块指针以在 NSArray 中添加和删除
- node.js - 合并聚合并在 MongoDB 中查找结果
- javascript - Javascript - Vue,无法让搜索过滤器对对象数组起作用