检查string格式

我有一个循环,循环列中的所有条目:

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 

我需要检查我的tempDatestringvariables是在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 

正如你所看到的细胞是一个string单元格,我需要确保tempDatestring将在我做转换或应用程序将下降之前正确的格式。

我想显示用户消息,在单元格( )他有不正确的数据

或者也许尝试Catch块转换 – 但我没有停止代码执行后第一个错误

试试这个(UNTESTED)

 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