Excel 2007 VBA根据日期查找行

时间:2009-12-30 17:25:29

标签: excel-vba excel-2007 vba excel

Date | data | data | data
12/29|   G  |   F  |  G
12/30|   G  |      |

我有一个像上面这样的电子表格。我想找到当前日期的行,然后在Range类型中引用当前日期的行。然后循环遍历该行中的数据。

我可以找到当前日期,并获取当前日期的单元格地址:

dateRange = "A1:" & regionSheet.Range("A1").End(xlDown).Address

    For Each cell In regionSheet.Range(dateRange)
      If cell.Value = Date Then
      row = cell.Address
      End If
    Next cell

返回$ 2 $。我需要以某种方式将其转换为Range类型。我尝试使用cell.Address如下:

row = cell.Address & ":" & regionSheet.Range(row).End(xlRight).Address

但错误了。

也许我会以错误的方式解决这个问题?有任何想法吗?谢谢!

2 个答案:

答案 0 :(得分:2)

range(cell, cell.End(xlToRight)).Address 

OR

range(cell.Address, range(cell.Address).End(xlToRight)).Address 

编辑:如果您希望它以Range类型使用,您可以使用 range(cell, cell.End(xlToRight))

答案 1 :(得分:1)

如果数据中存在间隙,则警告End()函数可能返回不正确的结果。例如,如果第二列和第四列中有数据,End将不会为您提供所需的结果。

您可以尝试这样的事情(假设您的数据从第1行和第1列开始):

Sub RowOfCurrentDate()

    Dim lngCurrDateRow As Long
    Dim lngNumCols As Long

    Dim rngDates As Range
    Dim rngToday As Range
    Dim c As Range

    'Get current region and count the number of columns
    Set rngDates = Range("A1").CurrentRegion
    lngNumCols = rngDates.Columns.Count

    'Resize the range down to one column
    Set rngDates = rngDates.Resize(rngDates.Rows.Count, 1)

    'Find today's date in the range
    lngCurrDateRow = Application.WorksheetFunction.Match(CLng(Date), rngDates, 0)

    'Set the range to search through for today
    Set rngToday = Range(Cells(lngCurrDateRow, 1), Cells(lngCurrDateRow, lngNumCols))

    'then loop through all cells in that range
    For Each c In rngToday
        'if cell is not empty
        If Len(c) > 0 Then
            'do something
        End If
    Next c

End Sub