如果特定单元格格式不是每小时格式
,我想应用条件(删除行)我尝试了以下代码,但它不起作用
Sub delete_row()
Dim i As Integer
Dim LR As Long
LR = Range("A" & Rows.Count).End(xlUp).Row
For i = 1 To LR
If Not Cells(i, 1).Value Like "##:##-##:##" Then
Cells(n, 1).EntireRow.Delete
End If
Next i
End Sub
答案 0 :(得分:1)
我不相信有一种开箱即用的方式或单一的模式匹配来评估您输入它的时间范围。
这应该可以工作,并且足够灵活,可以容纳一些输入变化(短划线之前或之后的空格,单位或双位小时输入(没有前导0)):
' Check for cell values matching the following Time pattern entry:
' [Hour]:[Minute]-[Hour]:[Minute]
Dim i As Integer
Dim LR As Long
LR = Range("A" & Rows.Count).End(xlUp).Row
Dim valueParts As Variant
Dim result As Boolean
Dim part As Integer
' Because you are deleting rows as you go,
' move from bottom to top.
' Otherwise rows will be skipped when you delete.
For i = LR To 1 Step -1
' Split into parts so we can check each.
valueParts = Split(Cells(i, 1).Value, "-")
' Evalutate each component to make sure
' it fits the time format we expect.
' Default to True until a non-match is found.
result = True
For part = LBound(valueParts) To UBound(valueParts)
' Account for single digit (0-9)
' and double digit (10-12) hours.
result = result And _
(Trim(valueParts(part)) Like "#:##" _
Or Trim(valueParts(part)) Like "##:##")
Next
If Not result Then
' This is not a valid time pattern.
' Delete the row.
Rows(i).Delete
End If
Next
答案 1 :(得分:1)
我会这样做:
Sub DeleteRow()
Dim i As Integer
For i = Range("A" & Rows.Count).End(xlUp).Row To 1 Step -1
If Range("A" & i).NumberFormat = "hh:mm AM/PM" Then //Update format to suit your needs
Range("A" & i).EntireRow.Delete
End If
Next i
End Sub
从值列的底部开始并向上工作,检查单元格格式并根据需要删除。
答案 2 :(得分:0)
添加以下代码,我希望这符合您的要求
但是,为了顺利运行以下代码,我希望您的时间值格式为 TIME 。
我刚添加了附加函数 IsTime ,它检查单元格值,如果单元格值是时间值,则返回TRUE / FALSE。在这里,您不必担心特定的小时格式,您只需关注单元格是否格式化为 TIME 。
Sub delete_row()
Dim i As Integer
Dim LR As Long
Dim res As Boolean
LR = Range("A" & Rows.Count).End(xlUp).Row
For i = 1 To LR
res = IsTime(Cells(i, 1))
If res = False Then
Cells(i, 1).EntireRow.Delete
End If
Next i
End Sub
Function IsTime(rng As Range) As Boolean
Dim sValue As String
sValue = rng.Cells(1).Text
On Error Resume Next
IsTime = IsDate(TimeValue(sValue))
On Error GoTo 0
End Function