VBA代码添加单元格包含日期,而单元格包含数字,出现不匹配错误

时间:2018-06-29 19:22:36

标签: excel vba excel-vba type-mismatch

嗨,我正在尝试将单元格加在一起并将它们与另一个单元格进行比较,但是我遇到类型不匹配的情况。 第一个单元格是一个日期,要添加的一个单元格是一个“天数”,而要比较的第三个单元格也是一个日期。 但我得到类型不匹配。 我的代码在下面

Sub Macro1()
Macro1 Macro

    Dim wks As Worksheet
    Set wks = ActiveSheet

    Dim x As Integer
    Dim p As Integer

    Dim rowRange As Range
    Dim colRange As Range

    Dim LastCol As Long
    Dim LastRow As Long
    LastRow = wks.Cells(wks.Rows.Count, "A").End(xlUp).Row

    Set rowRange = wks.Range("A1:A" & LastRow)

    For i = 7 To 189
        p = 0
        For q = 8 To LastRow
            If [aq] = [si] Then
                If [cq] + [ui] >= [xi] Then
                    [oq] = 1
                Else
                    p = p + [dq]
                    [qq] = 0
                End If
             End If
         Next q     
     Next i   
End Sub 

[cq]是一个包含日期的单元格

[ui]是一个包含数字的单元格

[xi]是一个包含日期的单元格

2 个答案:

答案 0 :(得分:2)

尝试使用cells(q, "A") = cells(i, "S")

    For i = 7 To 189
    p = 0
    For q = 8 To LastRow
         'If [aq] = [si] Then
         If cells(q, "A") = cells(i, "S") Then
            'If [cq] + [ui] >= [xi] Then
            If cells(q, "C") + cells(i, "U") >= cells(i, "X") Then
                '[oq] = 1
                cells(q, "O") = 1
            Else
                'p = p + [dq]
                p = p + cells(q, "D")
                '[qq] = 0
                cells(q, "Q") = 0
            End If
         End If
         Next q

      Next i   

答案 1 :(得分:0)

您需要使用“ DateAdd”功能。这里的说明:https://www.techonthenet.com/excel/formulas/dateadd.php

示例:

Sub add_dates()


    Dim dateOne As Date
    Dim dateTwo As Date
    Dim lngDays As Long


    dateOne = "1/1/2018"
    lngDays = 2
    dateTwo = "1/3/2018"

    Dim result As Boolean
    If DateAdd("d", lngDays, dateOne) >= dateTwo Then
        MsgBox ("Greater than or equal to")
    Else
        MsgBox ("Less than")
    End If


End Sub