我有一列20行。该列的标题为“ MONTH”。在前10行中,单元格包含文本“ Jan”。在接下来的10行中,单元格包含日期“ 18-12-2019”。我想编写一个宏,该宏将从A2开始遍历该列,并将在包含日期的单元格处停止。
我写了以下代码。但这是行不通的。 Excel在说,“功能未定义。”请帮我为此写正确的代码。
Sub Find_Date()
Dim cell As Range
Dim Rng As Range
Set Rng = Range(("A2"), Range("A2").End(xlDown))
For Each cell In Rng
If IsText(cell) = True Then: cell.Offset(1, 0).Select
Next
End Sub
答案 0 :(得分:0)
根据您所描述的情况:
在前10行中,单元格包含文本“ Jan”。在接下来的10行中,单元格包含日期
以下代码将是一种解决方法:
Sub Find_Date()
Dim row As Integer
For row = 2 To 10
'Do whatever you want with activesheet.cells(row,1)
Next
End Sub
您到底想对这些细胞做什么?
答案 1 :(得分:0)
这是另一个更具动态性和灵活性的解决方案...
但是,使用这种方法不能跳过单元格行。
Sub Find_Date()
Dim row As Integer
For row = 2 To ActiveSheet.Cells(1,1).End(xlDown).Row
'Use ActiveSheet.Cells(row, 1) to control the current cell (1 = First Column)
If IsDate(ActiveSheet.Cells(row, 1).Value) = TrueThen
' Add Code Here to be executed if there is Date
Else
' Add Code Here to be executed if there is TEXT
End If
Next
End Sub
同样,上面的代码在修改上面的内容之前实际上不会做任何事情。
下面是一批代码,这些代码将简单地选择“ A”列中所有作为日期的单元格。
Sub Find_Date()
Dim row As Integer
Dim y() As Variant
Dim z As Integer
z = 1
For row = 2 To ActiveSheet.Cells(1, 1).End(xlDown).row
If IsDate(ActiveSheet.Cells(row, 1).Value) = True Then
ReDim Preserve y(1 To z) As Variant
y(z) = ActiveSheet.Cells(row, 1).Address
z = z + 1
End If
Next
For Each x In y
ranges = ranges + x + ", "
Next x
Range(Left(ranges, Len(ranges) - 2)).Select
End Sub
答案 2 :(得分:0)
尝试一下:
Option Explicit
Sub test_only() 'Only for test
Dim Rng As Range
Dim dateCell As Range
Set Rng = Range(("A2"), Range("A2").End(xlDown)) 'Set range as desired
Set dateCell = Find_Date(Rng)
Debug.Print dateCell.Address 'dateCell now holds the first non-text cell (range)
End Sub
Function Find_Date(Rng As Range) As Range
Dim cell As Range
Set Find_Date = Nothing
For Each cell In Rng
If WorksheetFunction.IsText(cell) = False Then
Set Find_Date = cell
Exit Function
End If
Next
End Function