gpt4 book ai didi

excel - 如何使用 VBA 宏将日期字段的月份和年份值与字符串匹配?

转载 作者:行者123 更新时间:2023-12-04 03:26:04 26 4
gpt4 key购买 nike

我有一张工作表,其中第一列包含可以采用任何日期格式的日期。我需要将日期以 MMM-yy 的字符串格式传递到函数中以获取单元格地址,但我最终得到错误 2042 或类型不匹配,因为我正在尝试比较字符串和日期。鉴于这种情况,我该如何解决类型转换问题?我的功能分享如下:

 Function getcellAddress(ByVal col As String, ByVal row As String) As Range
Dim r, c As Variant
Dim maxRowCount As Integer

With ActiveSheet
r = Application.Match(row, Format(.Columns("A"), "MMM-yy"), 0)
c = Application.Match(col, .Rows(1), 0)

'add new record when company not found
If IsError(r) And IsAllOther = False Then
r = 65636
c = 256
End If
Set getcellAddress = .Cells(r, c)

End With

End Function

下面是我在子过程中调用此函数的方式:

Dim lookUp As String
lookUp = getcellAddress("A", "May-21").Offset(-1, 0).Address

样本日期列的日期如下

    A
1 Jan-21
2 Feb-21
3 Mar-21
4 Apr-21
5 May-21

预期的输出需要是 A5。

最佳答案

一旦您更改了我在 previous question 中提到的日期,试试这个简单的代码来实现你想要的。视情况而定。

Option Explicit

Sub Sample()
Dim r As Range

Set r = getcellAddress("Sep-21", "A")

If Not r Is Nothing Then
MsgBox r.Address
Else
MsgBox "Not Found"
End If
End Sub

Function getcellAddress(searchString As String, Col As String) As Range
Dim CurrentRow As Variant

CurrentRow = Application.Match(searchString, Columns(Col), 0)

If Not IsError(CurrentRow) Then
Set getcellAddress = Range(Col & CurrentRow)
End If
End Function

enter image description here

关于excel - 如何使用 VBA 宏将日期字段的月份和年份值与字符串匹配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67594122/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com