vba - 检查字符串格式

标签 vba excel

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

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 字符串的格式正确,否则应用程序将失败。

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

或者可能是转换时的 Try Catch block - 但我在第一个错误后未能停止代码执行

最佳答案

试试这个(未经测试)

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

关于vba - 检查字符串格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21452922/

相关文章:

ms-access - 全局点击事件处理程序(WithEvents)

c++ - 字符串的变体数组包含备用空格

java - 如何在 Apache POI 中创建 XSFTable

excel - Office.js javascript API中基于C#的excel函数可能吗?

vba - 使用 VBA 获取阈值

VBA - 转到网站并从保存提示下载文件

vba - 复制工作表,根据范围重命名工作表,并根据范围编辑复制的工作表

c# - 在 C# 中使用 EPPLUS 设置列数据格式

excel - 在 INDEX(MATCH(COUNTIF())) 公式中处理标准字符处的通配符

vba - 应用程序定义或对象定义的错误与公式