【问题标题】:How do I match the month & year value of the date field with string using VBA Macro?如何使用 VBA 宏将日期字段的月份和年份值与字符串匹配?
【发布时间】:2021-05-18 21:22:32
【问题描述】:

我有一张表格,其中第一列包含可以采用任何日期格式的日期。我需要将 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。

【问题讨论】:

  • 在你上一个问题之后,我相信你已经不需要Format(.Columns("A"), "MMM-yy")了?
  • 问题在于Format(.Columns("A"), "MMM-yy") 不能在格式中使用多单元格范围。最好的办法是在该列中加载一个已使用范围的数组,然后迭代该数组直到找到正确的日期。
  • 您的“日期”是实际日期,还是看起来像日期的文本?
  • 他们是蒂姆的实际日期。

标签: excel vba


【解决方案1】:

一旦您更改了我在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

【讨论】:

  • 是的,我正在考虑另一种解决方案,但您的两个答案都正常运行。谢谢 Sid,非常感谢您的帮助。
猜你喜欢
  • 2020-01-24
  • 2020-12-19
  • 2018-07-12
  • 1970-01-01
  • 2012-02-17
  • 2021-09-11
  • 1970-01-01
  • 2021-10-15
  • 2023-03-03
相关资源
最近更新 更多