提问人:rxex 提问时间:2/16/2023 最后编辑:Communityrxex 更新时间:8/20/2023 访问量:42
匹配以在列表中查找日期会根据日期的格式产生不同的答案
Match to find a date in a list yields different answers depending on the formatting of the dates
问:
我在 A 列上有一个按升序排序的日期列表(工作日,没有周末)。该列有一个字符串标题,内容为“Dates”。列的格式为 m/d/yyyy。
第一个日期是 1998 年 5 月 28 日,单元格 A2。
最后日期是 2023 年 2 月 9 日,单元格 A6216。
我的日期是 6 年 28 月 1999 日,在单元格 AG275 上。我需要在 A 列上找到该日期的行。
此代码查找日期,只要列 A 和单元格 AG275 的格式都设置为常规即可。
在这种情况下,单元格 AG275 读取为 36337,答案(下面代码中的变量 a)返回 275,即 36337 所在的行。
Sub findDate()
Dim dateToFind
Dim arr()
Dim Rng As Range
dateToFind = Cells(275, "ag").Value
Set Rng = Worksheets("calcSheet").Range("A1:A6216")
arr = Rng
a = WorksheetFunction.Match(dateToFind, arr, 1)
End Sub
问题在于,如果列 A 和单元格 AG275 的格式都设置为短日期,则代码答案(变量 a)不是 275,而是 1530,即 2004 年 6 月 25 日,在一般格式中为 38163(单元格 A1531 上的以下日期是 2004 年 6 月 28 日)。
我可以在开始代码之前添加代码来重新格式化所有内容,并使用数字而不是日期,但我宁愿使用给定的日期。
如果所有内容都格式化为短日期,我该如何得到答案?
我怀疑问题可能与我声明变量和数组的方式有关。我尝试声明为 Date、Variant、Long 和 Integer。
正如我在相关帖子中读到的那样,我也尝试过,
dateToFind = CDate(Cells(275, "ag").Value)
和
dateToFind = CLng(CDate(Cells(275, "ag").Value))
对于长日期 (mm/dd/yyyy),行为是相同的。
答:
1赞
wrbp
2/20/2023
#1
如果单元格的内容是日期,而要查找的单元格的内容是日期,则格式化不论,以下方法将起作用:
Sub findDate()
Dim dateToFind As Variant
Dim Rng As Range
dateToFind = Cells(275, "ag")
Set Rng = Worksheets("calcSheet").Range("A1:A6216")
a = Application.Match(CLng(dateToFind), Rng, 1)
End Sub
下一个:使用多个条件在二维数组中搜索值
评论
arr = Rng.Value2: a = WorksheetFunction.Match(CDbl(dateToFind), arr, 1)