2016-05-17 78 views
0

所以我有一個代碼下面的代碼循環圍繞一組單元格的小數值,根據輸入單元格的值給出不同的結果。我試圖添加一個子句,以便如果其中一個輸入單元格爲空,結果也是空的。選擇案例VBA空單元格

這是我的代碼:

Sub JEeldepthoutlet() 
    Dim score As Double, result As String 
    Dim Rng As Range, i As Long 

i = 0 

With Sheets("Velocity_Depth") 
    For Each Rng In .Range("B12:B16") 
     score = Rng.Value 
     Select Case score 
    Case Is >= 0.05 
     result = "1" 
    Case Is >= 0.031 
     result = "0.6" 
    Case Is >= 0.021 
     result = "0.3" 
    Case Is >= 0 
     result = "0" 
     End Select 
     .Range("Q31").Offset(i).Value = result 
     i = i + 1 
    Next Rng 
End With 
End Sub 

我試圖添加兩個下列選項中,這兩者都不工作:

Case Else 
result "" 

這正好給了我一個結果爲0,如果有空單元格

我也試過

Case "" 
Exit Sub 

這也給了我的結果0.

有沒有人有任何想法?在此先感謝

回答

1

使用爲0.

爲了避免我在Select Case之前添加了if語句

對於空單元格,我在所有其他情況下分配了單元格值的情況下在case語句中使用的範圍外分配了一個值。見下:

If ActiveCell = "" Then 

    score = 101 

Else 

    score = ActiveCell 

End If 

Select Case score 

    Case 0 To 35 
     Mark = "F" 
     Comment = "Terrible - needs attention" 
    Case 36 To 50 
     Mark = "D" 
     Comment = "Needs attention" 
    Case 51 To 65 
     Mark = "C" 
     Comment = "Not bad, could do better" 
    Case 66 To 85 
     Mark = "B" 
     Comment = "Good score" 
    Case 86 To 100 
     Mark = "A" 
     Comment = "EXcelent score - well done!" 
    Case Else 
     Mark = "" 
     Comment = "NO SCORE RECORDED" 

End Select 
1

裹在if語句整個選擇的情況:當您保存一個空單元格爲它存儲的數值變量

Sub JEeldepthoutlet() 
    Dim score As Variant, result As String 
    Dim Rng As Range, i As Long 

    i = 0 

    With Sheets("Velocity_Depth") 
     For Each Rng In .Range("B12:B16") 
      score = Rng.Value 
       Select Case score 
        Case Is = "" 
         result = "" 
        Case Is >= 0.05 
         result = "1" 
        Case Is >= 0.031 
         result = "0.6" 
        Case Is >= 0.021 
         result = "0.3" 
        Case Is >= 0 
         result = "0" 
       End Select 
      .Range("Q31").Offset(i).Value = result 
      i = i + 1 
     Next Rng 
    End With 
End Sub 
+0

當我這樣做時,它會出現類型不匹配錯誤,但我將分數改爲「變體」,它的工作完美。感謝您的幫助Scott,我正在嘗試爲自己的項目教授自己的VBA。 – Lilou

+0

@Lilou給Gary的學生正確的答案並使用他的。 –

0

Sub JEeldepthoutlet() 
Dim score As Double, result As String 
Dim Rng As Range, i As Long 

i = 0 

With Sheets("Velocity_Depth") 
    For Each Rng In .Range("B12:B16") 
     score = Rng.Value 
     If score <> "" Then 
      Select Case score 
       Case Is >= 0.05 
        result = "1" 
       Case Is >= 0.031 
        result = "0.6" 
       Case Is >= 0.021 
        result = "0.3" 
       Case Is >= 0 
        result = "0" 
      End Select 
     Else 
      result = "" 
     End If 
     .Range("Q31").Offset(i).Value = result 
     i = i + 1 
    Next Rng 
End With 
End Sub