我很擅长excel vba,这是我为满足以下条件所写的内容
是我将手动输入的数字。
Dim gr As Range
Dim yr As Range
Dim rr As Range
Dim gr1 As Long
Dim yr1 As Long
Dim rr1 As Long
Dim overallrisk As Range
Set overallrisk = Sheets("Dashboard").Range("C24")
Set gr = Sheets("Dashboard").Range("C30:C32").Range("C33:C35").Range("D33:D35")
Set yr = Sheets("Dashboard").Range("C27:C29").Range("D30:D32").Range("E33:E35")
Set rr = Sheets("Dashboard").Range("D27:D29").Range("E27:E29").Range("E30:E32")
gr1 = Application.WorksheetFunction.Sum(gr)
yr1 = Application.WorksheetFunction.Sum(yr)
rr1 = Application.WorksheetFunction.Sum(rr)
If gr1 > yr1 Or rr1 Then
overallrisk = "G"
ElseIf yr1 > gr1 Or rr1 Then
overallrisk = "Y"
ElseIf rr1 > yr1 Or gr1 Then
overallrisk = "R"
End If
我没有得到任何错误所以我认为它会起作用但是“整体风险”单元格仍然是空白的,即使我将数字放在单元格的范围内。
谢谢!
答案 0 :(得分:1)
我认为问题是你最后的If
声明。你有:
If gr1 > yr1 Or rr1 Then
我相信你的意思是:
If (gr1 > yr1) Or (gr1 > rr1) Then
Excel在OR
之后查看您的条件,并将其作为单独的语句进行评估。你想要:
If gr1 > yr1 Or gr1 > rr1 Then
overallrisk = "G"
ElseIf yr1 > gr1 Or yr1 > rr1 Then
overallrisk = "Y"
ElseIf rr1 > yr1 Or rr1 > gr1 Then
overallrisk = "R"
End If
答案 1 :(得分:0)
这将清理您的代码,使其更具可读性,并且应该允许它正常工作!
Dim gr As Range, yr As Range, rr As Range
Dim gr1 As Long, yr1 As Long, rr1 As Long
Dim overallrisk As Range
Dim wks As Worksheet
Set wks = Sheets("Dashboard")
With wks
Set overallrisk = .Range("C24")
Set gr = .Range("C30:C32,C33:C35,D33:D35")
Set yr = .Range("C27:C29,D30:D32,E33:E35")
Set rr = .Range("D27:D29,E27:E29,E30:E32")
gr1 = Application.WorksheetFunction.Sum(gr)
yr1 = Application.WorksheetFunction.Sum(yr)
rr1 = Application.WorksheetFunction.Sum(rr)
If gr1 > yr1 Or gr1 > rr1 Then
overallrisk.Value = "G"
ElseIf yr1 > gr1 Or yr1 > rr1 Then
overallrisk.Value = "Y"
ElseIf rr1 > yr1 Or rr1 > gr1 Then
overallrisk.Value = "R"
End If
End With