sub financials
dim g as long
dim r as long
dim y as long
dim oh as range
dim vr as range
dim sum as long
set vr = Sheets("Financials").Range("B5:B53")
set oh = sheets("Financials").Range("B2")
y = application.worksheetfunction.countif(vr, "y")
g = application.worksheetfunction.countif(vr, "g")
r = application.worksheetfunction.countif(vr, "r")
if g = 5 then
oh = "G"
elseif g = 4 and y = 1 then
oh = "G"
elseif r>=2 then
oh = "R"
elseif y >= 1 and r>= 1 then
oh = "R"
elseif y >=3 then
oh = "R"
elseif g=3 and y=2 then
oh = "Y"
elseif g=4 and r=1 then
oh = "Y"
elseif g=2 and y=3 then
oh = "Y"
elseif y=2 then
oh = "Y"
end if
end sub
这是我到目前为止所写的,它工作正常,但你可以看到有5个细胞确定整个细胞。但我已经意识到有时候只有不到5个细胞 - 有时只有2个或3个。如果少于5个,这个公式不适用,因为它需要5个细胞来确定整个细胞
我在想使用sum函数。所以总结y,g,r的countifs,如果这个总和等于1,2,3那么它将执行以下命令,但我不知道该怎么做
如果y,g,r = 3的总和则执行以下操作:
if g = 3 then
oh = "G"
elseif g = 1 and y = 2 then
oh = "Y"
elseif g = 2 and r = 1 then
oh = "Y"
elseif g =1 and y = 1 and r =1 then
oh = "R"
elseif y = 2 and r = 1 then
oh = "R"
elseif r = 3 then
oh = "R"
如果y,g,r = 2之和,则执行以下操作:
if g = 2 then
oh ="G"
elseif g = 1 and y = 1 then
oh = "y"
elseif y = 1 and r =1 then
oh = "R"
等
我还需要锁定工作表,但宏必须继续运行。我该怎么做?
答案 0 :(得分:2)
获取单元格的总和后,可以使用选择案例。对于这个例子,我会使用select case,因为它比使用ifs和ifs更适合我,但这是个人偏好。有关选择案例检查的更多示例here
锁定工作表需要一行:
sheets("worksheetname").protect userinterfaceonly:=True
有关工作表锁定的更多信息,请查看此link
Sub financials()
Dim g As Long
Dim r As Long
Dim y As Long
Dim oh As Range
Dim vr As Range
Dim sum As Long
Dim i
Set vr = Sheets("Financials").Range("B5:B53")
Set oh = Sheets("Financials").Range("B2")
y = Application.WorksheetFunction.CountIf(vr, "y")
g = Application.WorksheetFunction.CountIf(vr, "g")
r = Application.WorksheetFunction.CountIf(vr, "r")
x = y + g + r
Select Case x
Case Is = 5
If g = 5 Then
oh = "G"
ElseIf g = 4 And y = 1 Then
oh = "G"
ElseIf r >= 2 Then
oh = "R"
ElseIf y >= 1 And r >= 1 Then
oh = "R"
ElseIf y >= 3 Then
oh = "R"
ElseIf g = 3 And y = 2 Then
oh = "Y"
ElseIf g = 4 And r = 1 Then
oh = "Y"
ElseIf g = 2 And y = 3 Then
oh = "Y"
ElseIf y = 2 Then
oh = "Y"
End If
Case Is = 3
If g = 3 Then
oh = "G"
ElseIf g = 1 And y = 2 Then
oh = "Y"
ElseIf g = 2 And r = 1 Then
oh = "Y"
ElseIf g = 1 And y = 1 And r = 1 Then
oh = "R"
ElseIf y = 2 And r = 1 Then
oh = "R"
ElseIf r = 3 Then
oh = "R"
End If
Case Is = 2
If g = 2 Then
oh = "G"
ElseIf g = 1 And y = 1 Then
oh = "y"
ElseIf y = 1 And r = 1 Then
oh = "R"
End If
'more cases here
End Select
End Sub