Excel精英培训网

 找回密码
 注册
数据透视表40+个常用小技巧,让你一次学会!
查看: 3891|回复: 4

[已解决]countif函数在不连续range使用错误该如何解决?

[复制链接]
发表于 2015-2-2 10:42 | 显示全部楼层 |阅读模式
有两段不连续数据,我合并为一个range,然后用countif函数查找个数,结果提示错误。如果是连续的两段数据却可以合并且用函数计算,请高手帮忙解答。
1
1
3
3
3
7
2
1
4
6
数据代码:
dim r1,r2,rr as range
set r1=range(cells(1,1),cells(4,1))
set r2=range(cells(6,1),cells(10,1))                   '如果改为“set r2=range(cells(5,1),cells(10,1))”则可以正常运行
set rr=application.union(r1,r2)
for gs=1 to 5
    cells(gs,2)=gs
    cells(gs,3)=application.worksheetFuction.countif(rr,"="&gs)
next gs
最佳答案
2015-2-2 23:42
本帖最后由 adders 于 2015-2-2 10:44 编辑

CountIf does work with 不连续数据.

Change code to:

Sub pxt()
Dim r1 As Range, r2 As Range, rr As Range
Dim gs As Long, i As Long

Set r1 = Range(Cells(1, 1), Cells(4, 1))
Set r2 = Range(Cells(6, 1), Cells(10, 1))
Set rr = Application.Union(r1, r2)

For gs = 1 To 5
    Cells(gs, 2) = gs
    With Application.WorksheetFunction
        If rr.Areas.Count = 1 Then
            Cells(gs, 3) = .CountIf(rr, gs)
        Else
            Cells(gs, 3) = 0
            For i = 1 To rr.Areas.Count
                Cells(gs, 3) = Cells(gs, 3) + .CountIf(rr.Areas(i), gs)
            Next i
        End If
    End With
Next gs

End Sub

excel精英培训的微信平台,每天都会发送excel学习教程和资料。扫一扫明天就可以收到新教程
发表于 2015-2-2 11:03 | 显示全部楼层
建议:
1)上传附件,并给出部分效果
2)实际内容是数字吗?如果是,有范围吗?
回复

使用道具 举报

发表于 2015-2-2 23:42 | 显示全部楼层    本楼为最佳答案   
本帖最后由 adders 于 2015-2-2 10:44 编辑

CountIf does work with 不连续数据.

Change code to:

Sub pxt()
Dim r1 As Range, r2 As Range, rr As Range
Dim gs As Long, i As Long

Set r1 = Range(Cells(1, 1), Cells(4, 1))
Set r2 = Range(Cells(6, 1), Cells(10, 1))
Set rr = Application.Union(r1, r2)

For gs = 1 To 5
    Cells(gs, 2) = gs
    With Application.WorksheetFunction
        If rr.Areas.Count = 1 Then
            Cells(gs, 3) = .CountIf(rr, gs)
        Else
            Cells(gs, 3) = 0
            For i = 1 To rr.Areas.Count
                Cells(gs, 3) = Cells(gs, 3) + .CountIf(rr.Areas(i), gs)
            Next i
        End If
    End With
Next gs

End Sub

回复

使用道具 举报

 楼主| 发表于 2015-3-12 10:43 | 显示全部楼层
谢谢,可以解决,按不同区域统计也是一个法子。
回复

使用道具 举报

 楼主| 发表于 2015-3-12 10:47 | 显示全部楼层
本帖最后由 morethane 于 2015-3-12 10:54 编辑
爱疯 发表于 2015-2-2 11:03
建议:
1)上传附件,并给出部分效果
2)实际内容是数字吗?如果是,有范围吗?

实际内容不只是数字,没有具体范围,只是两个不连续的range不能用一个函数统计。

新建文件夹.rar

7.18 KB, 下载次数: 2

回复

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则

小黑屋|手机版|Archiver|Excel精英培训 ( 豫ICP备11015029号 )

GMT+8, 2024-5-3 02:04 , Processed in 0.158774 second(s), 11 queries , Gzip On, Yac On.

Powered by Discuz! X3.4

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表