VBA EXCEL:在选择中循环遍历每个单元格时,查找方法不起作用


0

我正在尝试创建一个宏,在选择范围后,它将告诉我在样本中找到多少个20英尺或40英尺的容器。

范围选择

宏基本上查找字符串“1x20”或“1x40”,当找到任何一个时,变量cont20或cont40将增加1。

我有的代码:

Sub containercount()

Dim count20 As Integer
Dim count40 As Integer

count20 = 0
count40 = 0 

For Each cell In Selection

If Not ActiveCell.Find("1x20", LookAt:=xlPart, MatchCase:=False) Is Nothing Then
 count20 = count20 + 1
End If

If Not ActiveCell.Find("1x40", LookAt:=xlPart, MatchCase:=False) Is Nothing Then
 count40 = count40 + 1
End If

Next cell

MsgBox ("Number of 20ft containers: " & count20 & vbNewLine & "Number of 40ft containers: " & count40)

End Sub

但结果总是零......我将非常感谢你的帮助。

Answers:


1

它无法工作的原因是因为您正在搜索空数组。

选择应该被类似的东西取代 ActiveSheet.Selection

此外,你必须使用Cell.Find,而不是ActiveCellAciveCell对所选单元格的引用。

但无论如何,我只想使用CountIf公式而不是宏。


1
请举一个如何使用的例子CountIf
James Mertz

我现在不能,因为我没有在我的电脑上安装excell,我必须查找确切的格式。明天会这样做。任何其他人都可以查阅,随意评论,我会在答案中添加示例,并给予应有的信用。
LPChip

我刚换ActiveCell.Findcell.Find,它工作了!谢谢!顺便说一句,我不使用Countif,因为我会添加更多的字符串,然后VBA会更有效率。
鲁本

对。:)很高兴听到它固定。:)
LPChip 2014年
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.