我有一个工作表,其中A列列出了一系列风险。
列F列出了可以缓解这些风险的项目。 我想编写一个脚本来识别a中的风险是否有控制权或者没有控制权 例如
A F
Risk7 control
monitor
test
Risk8 (blank)
所以输出将是1风险控制和一风险没有
到目前为止我的脚本是Sub CountWithWithoutControls()
' counts number of risks with controls and without controls,
' currently running through each cell and comparing back to original control,
' need to write to get it to walk down the series
Dim cell As Range
Dim myrange As Range
Dim control As Long
Dim WoControl As Long
Set myrange = Range("a7:f27")
For Each cell In myrange
If Range("c7") <> "" And Range("f7") = "Control" Then control = control + 1
If Range("c7") <> "" And Range("f7") <> "Control" Then WoControl = WoControl + 1
Next cell
MsgBox control & " = number of risks with controls" & WoControl & (" = number of risks without controls")
End Sub
我是VBA的新手,虽然我认为这不应该那么难,但我没有取得任何进展。任何正确方向的提示都将非常感激! 谢谢你们 保罗
答案 0 :(得分:2)
我提出这个更正
For Each cell In range("F7:F27")
if cell.offset(,-3)<>"" then ' check if cell in column C is not empty
if cell = "Control" then control=control+1 else WoControl=WoControl+1
end if
Next cell
答案 1 :(得分:1)
以下代码应检查风险的每个“块”,以查看块中是否出现“Control”(不区分大小写)。
我不确定风险是在A列还是C列(似乎在问题和其他答案中都有提及)所以我使用常量来定义列并开始行 - 根据需要更改它们。 / p>
(已更新以允许数据中的空白行)
Sub CountWithWithoutControls()
Const RiskColumn As String = "C"
Const ControlColumn As String = "F"
Const StartAtRow As Long = 7
Dim r As Long
Dim ControlFound As Boolean
Dim control As Long
Dim WoControl As Long
Dim lastRow As Long
With ActiveSheet
lastRow = .Range(RiskColumn & .Rows.Count).End(xlUp).Row
r = .Range(ControlColumn & .Rows.Count).End(xlUp).Row
If lastRow < r Then
lastRow = r
End If
ControlFound = False
For r = StartAtRow To lastRow
If UCase(Trim(CStr(.Cells(r, ControlColumn).Value))) = "CONTROL" Then
ControlFound = True
End If
If Not IsEmpty(.Cells(r + 1, RiskColumn)) Then
'Store info for previous block each time we encounter a new "risk"
If ControlFound Then
control = control + 1
Else
WoControl = WoControl + 1
End If
ControlFound = False
End If
Next
'Store info for final "block"
If ControlFound Then
control = control + 1
Else
WoControl = WoControl + 1
End If
End With
MsgBox control & " = number of risks with controls, " & WoControl & " = number of risks without controls"
End Sub
答案 2 :(得分:0)
尝试下面的代码,我认为在您的情况下,最好在行上使用<PatternLayout pattern ="%d %level %m%ex%n%STATIC" />
循环,扫描 A列和列F 中的值(而不是整个范围)。
For