如何在 VBA 中使用 Do直到循环来选择具有当前日期的第一行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17343648/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use Do Until loop in VBA to select first row with the current date
提问by Patrick Foran
I have an excel sheet with dates at the beginning of each row in the format of 6/27/2013. I would like to be able to select all rows in the sheet that begin with today's current date, so I wrote the following code:
我有一个 excel 表格,每行开头都有日期,格式为 2013 年 6 月 27 日。我希望能够选择工作表中以今天当前日期开始的所有行,因此我编写了以下代码:
CurrentD = Format(Now(), "M/DD/YYYY")
Workbooks("01 StatorLine.xlsx").Sheets("Downtime tracking").Activate
Range("A4").Select
Do
ActiveCell.Offset(1, 0).Select
Loop Until ActiveCell.Value = CurrentD
It selects the first row that has data, and then should keep moving down the rows until the first row that has today's date is reached. The only problem is that the loop never recognizes the date despite the formats being exactly the same. I tried changing CurrentD to a number and then entering that number into the spreadsheet. When I run the macro in this case it will stop on that number, but for some reason when slashes are involved it won't recognize the cell value and continues looping. I have never used VBA before so any help would be appreciated. Seems like the solution should be pretty simple.
它选择有数据的第一行,然后应该继续向下移动行,直到到达具有今天日期的第一行。唯一的问题是尽管格式完全相同,但循环永远不会识别日期。我尝试将 CurrentD 更改为一个数字,然后将该数字输入到电子表格中。当我在这种情况下运行宏时,它将停止在该数字上,但由于某种原因,当涉及斜杠时,它不会识别单元格值并继续循环。我以前从未使用过 VBA,因此将不胜感激。似乎解决方案应该非常简单。
Thanks!
谢谢!
回答by Andy G
If you use Text
rather than Value
it will compare the formatted values.
如果您使用Text
而不是Value
它会比较格式化的值。
Loop Until ActiveCell.Text = CurrentD
回答by Whit Kemmey
The string "6/27/2013" and the date 6/27/2013 are not the same thing in Excel. Even though Excel is showing you a string representation of the date, internally it is storing it as a number. So you can't compare a string and a date, but you could do this:
字符串“6/27/2013”和日期 6/27/2013 在 Excel 中不是一回事。尽管 Excel 向您显示日期的字符串表示形式,但它在内部将其存储为数字。所以你不能比较字符串和日期,但你可以这样做:
CurrentD = Format(Now(), "M/DD/YYYY")
Workbooks("01 StatorLine.xlsx").Sheets("Downtime tracking").Activate
Range("A4").Select
Do
ActiveCell.Offset(1, 0).Select
Loop Until Format(ActiveCell.Value, "M/DD/YYYY") = CurrentD
Now you are comparing a string with a string.
现在您正在将字符串与字符串进行比较。