COUNTIF并打印计数的string

需要您的VBA专业知识来完成以下任务。 我需要在一个专栏上做一个“MACORS”城市标识,然后打印每个城市旁边的城市。 我有这个代码:

Public Sub CountLocation() Range("V2").Select Selection.End(xlDown).Select lastcell = ActiveCell.Address ActiveCell.Offset(2, 0).Value = "=countif(V2:" + lastcell + ", ""Zurich"")" ActiveCell.Offset(2, 1).Value = "Zurich" ActiveCell.Offset(3, 0).Value = "=countif(V2:" + lastcell + ", ""Armonk"")" ActiveCell.Offset(3, 1).Value = "Armonk" ActiveCell.Offset(4, 0).Value = "=countif(V2:" + lastcell + ", ""Hong Kong"")" ActiveCell.Offset(4, 1).Value = "Hong Kong" ActiveCell.Offset(5, 0).Value = "=countif(V2:" + lastcell + ", ""London"")" ActiveCell.Offset(5, 1).Value = "London" ActiveCell.Offset(6, 0).Value = "=countif(V2:" + lastcell + ", ""Madrid"")" ActiveCell.Offset(6, 1).Value = "Madrid" End Sub 

我的问题是,我在一张纸上有大约90个“可能”的城市,与其他纸张不同。 我上面的代码打印不在特定工作表中的城市。

谢谢你的帮助

把城市放在一个数组中,并循环该数组。 此外,计数范围作为一个范围。 有一个如果testing大于0,所以不会写出城市,如果不存在。

全部一起:

 Option Explicit Public Sub CountLocation() Dim wb As Workbook Dim ws As Worksheet Dim countRange As Range Set wb = ThisWorkbook Set ws = wb.ActiveSheet 'Change as appropriate Dim lastRow As Long lastRow = ws.Range("V2").End(xlDown).Row 'Update: Extracted this into a variable Set countRange = ws.Range(ws.Cells(2, "V"), ws.Cells(lastRow, "V")) Dim Cities() Cities = Array("Zurich", "Armonk", "Hong Kong", "London", "Madrid") Dim city As Long Dim counter As Long Dim startRange As Range Set startRange = ws.Cells(lastRow, "V").Offset(2, 0) counter = 2 For city = LBound(Cities) To UBound(Cities) If Application.WorksheetFunction.CountIf(countRange, Cities(city)) > 0 Then startRange.Offset(counter, 0) = Application.WorksheetFunction.CountIf(countRange, Cities(city)) startRange.Offset(counter, 1) = Cities(city) counter = counter + 1 End If Next city End Sub 

各部分注释:

以下是从V2开始的V列中的空白单元格之前的最后一个使用的行。 如果在上次使用的单元格之前有空单元格,则会得到不正确的最后一行。

  lastRow = ws.Range("V2").End(xlDown).Row, "V") 

然后将范围设置为V2到V中最后一个使用的行,计算结果如下:

  Set countRange = ws.Range(ws.Cells(2, "V"),ws.Cells(lastRow, "V")) 

定义你将开始写出结果的地方:

 Set startRange = ws.Cells(lastRow, "V").Offset(2, 0) 

在计数范围内循环计算特定城市发生的城市arrays:

 Application.WorksheetFunction.CountIf(countRange, Cities(city)) 

在IF语句中将它包括,以确定count是否大于0。

 If Application.WorksheetFunction.CountIf(countRange, Cities(city)) > 0 

每次使用一个计数器variables写出到第一个粘贴位置偏移一行的页面:

  startRange.Offset(counter, 0) = Application.WorksheetFunction.CountIf(countRange, Cities(city)) startRange.Offset(counter, 1) = Cities(city)