Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/vba/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Vba 溢出和不匹配错误_Vba_Date_Row_Cell - Fatal编程技术网

Vba 溢出和不匹配错误

Vba 溢出和不匹配错误,vba,date,row,cell,Vba,Date,Row,Cell,我有一个For循环,它一直运行到有一个空白单元格为止。列A是自定义格式的数据。我正在试着每周(周一到周五)写一份报告 42738返回2017年1月3日 42739返回2017年4月1日 42740返回2017年1月5日 等等 我试图找出如何设置范围值来创建此周报 我测试的理论是A3-A2=1,这是周一到周二等 如果A3-A2=2,则表示周末 这就是我到目前为止的代码 Dim wks As Worksheet Dim LastDate As Long Dim myDate As Integer

我有一个For循环,它一直运行到有一个空白单元格为止。列A是自定义格式的数据。我正在试着每周(周一到周五)写一份报告

42738返回2017年1月3日

42739返回2017年4月1日

42740返回2017年1月5日

等等

我试图找出如何设置范围值来创建此周报

我测试的理论是A3-A2=1,这是周一到周二等

如果A3-A2=2,则表示周末

这就是我到目前为止的代码

Dim wks As Worksheet
Dim LastDate As Long
Dim myDate As Integer

Set wks = Worksheets("Labor")
LastDate = wks.Cells(wks.Rows.Count, "A").End(xlUp).Row

For dRow = 2 To LastDate

    xDate = CInt(Cells(dRow, "A").Value)
    yDate = CInt(Cells(dRow - 1, "A").Value)

    If xDate - yDate = 2 Then
        'weekend
        MsgBox ("Weekend!")

    ElseIf xDate - yDate = 1 Then
        'next day        
    ElseIf xDate - yDate = 0 Then
        'same day       
    Else
        MsgBox (xDate - yDate)

    End If


    myDate = 1

Next dRow
我的问题是:

如何修复xDate=的溢出错误

为什么yDate=不匹配错误

有没有更干净的方法来写这个


提前谢谢

假设列A中的日期值为数字格式(如您在文章中提到的42738、42739等),那么下面的代码将为您提供所需的内容

您不需要将日期值存储在变量中的单元格中,您可以使用
DateDiff
函数直接计算每两个单元格之间的差值。要了解有关日期差异的更多信息,请阅读

之后,您可以对要检查的每种类型的场景使用
Select Case

代码

Option Explicit

Sub NumofWeekdays()

Dim wks             As Worksheet
Dim LastDate        As Long
Dim NumofDays       As Long
Dim dRow            As Long

Set wks = Worksheets("Labor")    
With wks
    LastDate = .Cells(.Rows.Count, "A").End(xlUp).Row

    For dRow = 2 To LastDate
        NumofDays = DateDiff("d", .Range("A" & dRow - 1).Value, .Range("A" & dRow).Value)                          
        Select Case NumofDays
            Case Is >= 2
                'weekend
                MsgBox "Weekend!"

            Case 1
                'next day
                MsgBox "Next Day"

            Case 0
                'same day
                MsgBox "Same Day"

            Case Else
                MsgBox NumofDays

        End Select
    Next dRow
End With

End Sub

Dim myDate,因为longI能够使用DateDiff函数!这帮了大忙,谢谢你!