我有一个循环,循环列中的所有条目:
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字符串格式正确才能进行转换,否则应用程序将会崩溃。
我想显示用户消息,在Cell(,)中他有不正确的数据
或者在转换时可能是一个Try Catch块 - 但我在第一次错误
后未能停止代码执行答案 0 :(得分:3)
试试这个(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