简体   繁体   English

我收到类型不匹配错误

[英]I get Type Mismatch error

I'm have data sheet that contains year in A column, month in B column, day in C column and total count in d 我有一个数据表,其中A列包含年,B列包含月,C列包含天,d包含总数

I'm trying to create function that sums month today stats from d column 我正在尝试创建将d列中的当月统计数据相加的函数

    Function countMessagesbyDate(xYear As Integer, xMonth As Integer, xDay As Integer) As Integer

    Dim wsData As Worksheet
    Dim LastRow As Long
    Dim tMessages As Integer
    Dim rowYear As Range
    Dim rowMonth As Range
    Dim rowDay As Range
    Dim rowMessages As Range
    Dim rCell As Range
    Dim i As Integer

    Application.ScreenUpdating = False

    Set wsJData = ThisWorkbook.Sheets("daily_report")
    Set rowYear = wsData.Range("A1").End(xlDown).Row
    Set rowMonth = wsData.Range("B1").End(xlDown).Row
    Set rowDay = wsData.Range("C1").End(xlDown).Rows
    Set rowMessages = wsData.Range("D1:").End(xlDown).Rows

    tMessages = 0
    i = 0

    For Each rCell In rowYear
        i = i + 1
        If rCell.Value = xYear And rowMonth.Offset(i) = xMonth And rowDay.Offset(i) < Day(Today) Then
            tMessages = tMessages + rowMessages.Offset(i).Value
        End If
    Next rCell

    countMessagesbyDate = tMessages

    End Function

I get type missmatch when trying to set ranges. 尝试设置范围时出现类型不匹配的情况。 Can you please help? 你能帮忙吗?

Thanks in advance 提前致谢

You stated: - 您说:-

I get type missmatch when trying to set ranges 尝试设置范围时出现类型不匹配的情况

You have declared rowYear as a range ( Dim rowYear As Range ) but then supplied a number to it not a range, hence the mismatch. 您已将rowYear声明为范围( Dim rowYear As Range ),但随后Dim rowYear As Range提供了一个数字,而不是范围,因此不匹配。 Set rowYear = wsData.Range("A1").End(xlDown).Row will supply the row number not the range. Set rowYear = wsData.Range("A1").End(xlDown).Row将提供行号而不是范围。

To fix this either change the declaration: - 要解决此问题,请更改声明:-

Dim rowYear As Long

or change the setting of the variable: - 或更改变量的设置:-

Set rowYear = wsData.Range("A1").End(xlDown).Range

You declare this variable: 您声明此变量:

Dim wsData As Worksheet

but then you set this variable: 但是然后您设置此变量:

Set wsJData = ThisWorkbook.Sheets("daily_report")

Then you try to call the variable you Dim 'd, but the problem is that it is empty. 然后,您尝试调用Dim变量,但问题是它为空。

So if you change wsJData to wsData , your code will probably work. 因此,如果将wsJData更改为wsData ,则代码可能会起作用。

A simple Countifs() will do it for you instead of your UDF. 一个简单的Countifs()可以代替您的UDF来完成。

If you are very keen in using UDF why dont you use Countifs() in your UDF instead of looping through each cells. 如果您非常热衷于使用UDF,为什么不在UDF中使用Countifs()而不是遍历每个单元格。

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

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