0

我对 excel vba 很陌生,这就是我为满足以下条件而写的

  • sumA 大于 sumB 或 sumC 然后 "G"
  • sumB 大于 sumA 或 sumC 然后 "Y"
  • sumC 大于 sumA 或 sumB 然后 "R"

在 gr,yr,rr 单元格范围内是我将手动输入的数字。

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

我没有收到任何错误,所以我认为它会起作用,但是即使我在单元格范围内输入了数字,“overallrisk”单元格仍然是空白的。

谢谢!

4

2 回答 2

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 
于 2012-10-23T19:43:06.420 回答
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
于 2012-10-23T19:46:56.377 回答