2014-01-30 102 views
2

我有一個循環,該循環列中的所有條目:檢查字符串格式

Dim indexOfDATE As Integer 
indexOfDATE = 3 
Do Until indexOfDATE - 1 = Cells(Rows.Count, 2).End(xlUp).Row 
    Dim tempDate As String 
    tempDate = Replace(Sheets("Pirmie Ievaddati").Cells(indexOfDATE, 2).Value, ",", ".") 
    tempDate = Replace(tempDate, ".", "/") 
    indexOfDATE = indexOfDATE + 1 
Loop 

我需要檢查我的tempDate字符串變量處於DD.MM.YYYY格式我怎麼能做到這一點,如果沒有,顯示消息框,不會因爲錯誤而掉下來?

編輯:

我這樣做:

Dim indexOfDATE As Integer 
indexOfDATE = 3 
Do Until indexOfDATE - 1 = Cells(Rows.Count, 2).End(xlUp).Row 
    Dim tempDate As String 
    tempDate = Replace(Sheets("Pirmie Ievaddati").Cells(indexOfDATE, 2).Value, ",", ".") 
    tempDate = Replace(tempDate, ".", "/") 
    Dim current As Date 
    current = Format(CDate(tempDate), "dd/mm/yyyy") 
    Sheets("Pirmie Ievaddati").Cells(indexOfDATE, 2).Value = current 
    indexOfDATE = indexOfDATE + 1 
Loop 

正如你所看到的電池是一個字符串單元格,我需要確保tempDate字符串將是正確的格式之前,我轉換或應用程序將會下降。

我想告訴用戶消息,在細胞()他有不正確的數據

或者,也許一個上convertation try catch塊 - 但我失敗了第一個錯誤

+0

'dd.MM.yyyy'或'dd/MM/yyyy'? –

+0

檢查我的更新 – Cheese

+0

檢查我的回答:p –

回答

3
後停止執行代碼

試試這個(未經測試)

Dim indexOfDATE As Long 
Dim tempDate As String 
Dim current As Date 

indexOfDATE = 3 

Do Until (indexOfDATE - 1) = Cells(Rows.Count, 2).End(xlUp).Row 
    tempDate = Replace(Sheets("Pirmie Ievaddati").Cells(indexOfDATE, 2).Value, ",", "/") 

    If IsDate(tempDate) Then 
     current = Format(CDate(tempDate), "dd/mm/yyyy") 
     With Sheets("Pirmie Ievaddati").Cells(indexOfDATE, 2) 
      .NumberFormat = "dd/mm/yyyy" 
      .Value = current 
     End With 
     indexOfDATE = indexOfDATE + 1 
    End If 
Loop 

或者更短的版本

Dim indexOfDATE As Long 
Dim tempDate As String 
Dim current As Date 

indexOfDATE = 3 

With Sheets("Pirmie Ievaddati").Cells(indexOfDATE, 2) 
    Do Until (indexOfDATE - 1) = Cells(Rows.Count, 2).End(xlUp).Row 
     tempDate = Replace(.Value, ",", "/") 

     If IsDate(tempDate) Then 
      current = Format(CDate(tempDate), "dd/mm/yyyy") 
      .NumberFormat = "dd/mm/yyyy" 
      .Value = current 
      indexOfDATE = indexOfDATE + 1 
     End If 
    Loop 
End With