簡體   English   中英

VBA 循環 excel 中 A 列中的每個單元格

[英]VBA To loop each cell in the Column A in excel

在 A 列中的 excel 中,有一些日期格式和一些文本,我需要識別 A 列中的每個單元格是否是日期格式或不是日期格式:下面是我的代碼,我嘗試循環每個單元格,但是它僅識別單元格 A2、任何幫助和想法。 謝謝

   Dim strDate As String
         
   Dim rng As Range, cell As Range
   Set rng = Range("A2:A17")

    With ThisWorkbook.Worksheets("Feuil1")

    For Each cell In rng
    MsgBox (cell.Value)
    

    
    strDate = .Range("A2").Value
    If IsDate(strDate) Then
        MsgBox "This is a date format"
        
        Else
        MsgBox "This is not a date format"
         
       End If
       Next cell
   
    
     End With
      End Sub

這是因為您將 .range("A2") 分配給 strDate; 使用每個循環中的單元格 object :

Option Explicit

Public Sub CheckDates()

    Dim strDate As String
    Dim rng As Range, cell As Range
    
    Set rng = Range("A2:A17")
    With ThisWorkbook.Worksheets("Sheet1")
        For Each cell In rng
            MsgBox (cell.Value)
            strDate = cell.Value
            If IsDate(strDate) Then
                MsgBox "This is a date format"
            Else
                MsgBox "This is not a date format"
            End If
        Next cell
     End With
End Sub

如果您有很多行要檢查,最好使用更快的數組:

Sub test()
    
    Dim i As Long
    Dim arr As Variant
    
    With ThisWorkbook.Worksheets("Feuil1")
    
        arr = .Range("A2:A17")
        
        For i = LBound(arr) To UBound(arr)
        
            If IsDate(arr(i, 1)) Then
                MsgBox "This is a date format"
            Else
                MsgBox "This is not a date format"
            End If
            
        Next i
        
    End With
       
End Sub

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM