VBA:dynamicCountIf范围的语法

我会尽我所能去解释我的问题,但是在我的脑海中还是有些模糊,所以这可能不是那么清楚,对此我很抱歉。

以下是我遇到的问题的一部分:

If Application.WorksheetFunction.countif(Range("D:D"), Cells(x, firstcolumn).Value) _ And Application.WorksheetFunction.countif(Range("F:F"), Cells(x, firstcolumn).Value) _ And Application.WorksheetFunction.countif(Range("H:H"), Cells(x, firstcolumn).Value) Then 

这个项目背后的想法是检查“Cells(x,firstcolumn)”中的值是否同时存在于列D,F和H中,然后将值粘贴到其他位置。 然而,要检查“Cells(x,firstcolumn)”值的列数可以更改,所以需要在任意数量的列(2,10等)中检查值。 我的代码适用于指定的范围,但如果缺less或更多的添加,然后停止工作。

要检查的列始终与第一列偏移2,而第一列总是B,它将根据D,F,H等进行检查,而C,E,G等列有其他数据与此部分不相关。

我最好的猜测是有countif范围dynamic改变,但我在什么时候以及如何应该做的损失…

任何人都可以指出我为了实现这个目标而走向正确的方向吗? 如果需要,我可以发布完整的代码。

干杯!

你需要在这里提取一个函数。 像这样的东西:

 Private Function IsPresentInRange(ByVal source As Range, ByVal value As Variant) As Boolean IsPresentInRange = Application.WorksheetFunction.CountIf(source, value) > 0 End Function 

然后你需要一个方法来确定你需要给它一个source参数的范围 – 可以是它自己的函数,或者你可以在某个地方对它们进行硬编码; 基本上你想有一个范围组的概念来调用该函数 – 这将是最简单的:

 Private Function GetSourceRanges() As Collection Dim result As New Collection result.Add Range("D:D") result.Add Range("F:F") result.Add Range("H:H") 'maintain this list here Set GetSourceRanges = result End Function 

理想情况下,你可以在那里编写一些逻辑,这样你就不需要每次手动向该集合添加范围。

然后你可以迭代这些范围,并确定你是否得到所有的计数> 0:

 Dim sources As Collection Set sources = GetSourceRanges Dim result As Boolean result = True Dim sourceRange As Range For Each sourceRange In sources result = result And IsPresentInRange(sourceRange, Cells(x, firstcolumn).Value) Next If result Then ' whatever you had in that If block End If