简体   繁体   English

将if then命令输入到将遍历列的vba宏中

[英]Input an if then command into a vba macros that will loop through a column

I Am trying to make a macros that will look at the hour value of cells in a certain row, sort them based on my if, then, else criteria and produce a result based on this that will loop my column. 我正在尝试制作一个宏,该宏将查看特定行中单元格的小时值,并根据我的if,then,else条件对它们进行排序,并基于此条件生成结果,从而循环我的列。

So if the hour is <= 15 And >= 11, then result is "Lunch". 因此,如果小时数为<= 15并且> = 11,则结果为“午餐”。

I am very new to VBA, but here is what I have so far: 我是VBA的新手,但是到目前为止,这里是:

Sub Time_Sorter()

Dim i As Long
Dim result As String

For i = 1 To Rows.count            
    If Hour("J" & i) <= 15 And Hour("J" & i) >= 11 Then
        result = "Lunch"    
    ElseIf Hour("J" & i) <= 16 And Hour("J" & i) >= 17 Then
        result = "Pre-Dinner"    
    ElseIf Hour("J" & i) <= 18 And Hour("J" & i) >= 21 Then
        result = "Dinner"    
    ElseIf Hour("J" & i) <= 22 And Hour("J" & i) >= 23 Then
        result = "Late Night"
    Else
        result = "Other"    
    End If       
Next i

End Sub

I keep getting the message 我不断收到消息

Run-time error '13': Type mismatch 运行时错误“ 13”:类型不匹配

And I'm not sure how to fix it. 而且我不确定如何修复它。

Any insight would be very appreciated! 任何见解将不胜感激!

I think you are after something like the code below. 我认为您正在执行类似以下代码的操作。

Iv'e replaced your multiple ElseIf s with a constructed Select Case . 我用构造好的Select Case替换了您的多个ElseIf

Code

Sub Time_Sorter()

Dim i As Long
Dim result As String

' loop from the first row until last row with data in column ""j"
For i = 1 To Cells(Rows.Count, "J").End(xlUp).Row
    Select Case Hour(Range("J" & i).Value)
        Case 11 To 15
            result = "Lunch"
        Case 16 To 17
            result = "Pre-Dinner"
        Case 18 To 21
            result = "Dinner"
        Case 22 To 23
            result = "Late Night"
        Case Else
            result = "Other"
    End Select
Next i

End Sub

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM