2015-12-07 24 views
-2

我想將我們的運費價格放在工作簿1的單元格B14中。特定單元的運費價格

貨運價格變化的基礎上貨運重量:

  • 如果貨運重量小於45公斤,貨運價格55.00 HKD
  • 如果重量大於45公斤,貨運價格47.00 HKD
  • 如果重量超過百千克更大,運費價格是29.50港元

到目前爲止我在下面列出的VBA,但我得到the following errorstatement invalid outside Type block。如何使這項工作?

Public Function freightrate() 

    Weight As Double 
    freightrate As Double 

    Weight = Cells(B, 8).Value 
    freightrate = Cells(B, 14).Value 

    If Weight < 45 Then 
     freightrate = 55 
    ElseIf Weight > 45 < 100 Then 
     freightrate = 47 
    ElseIf Weight > 100 < 300 Then 
     freightrate = 29,50 
    End If 

End Function 
+1

嗨烏代,抱歉,但我們不goint解決從頭開始爲您解決問題。嘗試解決這個問題,我們將幫助使其工作並使其高效。 –

+0

>我得到錯誤消息指出波紋管功能programPublic freightrate() 重量爲雙 freightrate作爲雙人 重量=將細胞(B,8)。價值 freightrate =細胞(B,14)。價值 如果重量<45然後 freightrate = 55 elseif的重量> 45 <100然後 freightrate = 47 elseif的重量> 100 <300然後 freightrate = 29,50 結束如果 – Uday

+0

的代碼複製到原來的問題,它的格式正確和後也錯誤信息;而不是「ElseIf Weight> 45 <100」然後嘗試「ElseIf Weight> 45和Weight <100 Then」 – cboden

回答

0

哇,我的VBA時間很快回來。我認爲你在這裏有兩個問題,可變的定義和範圍。

1-定義變量,你錯過了Dim

Dim Weight As Double 

2。在VBA(see here)所使用的功能作爲返回值的名稱。我認爲是什麼造成你的麻煩是

freightrate As Double 

刪除它或使用臨時變量,它應該工作。

0

正如cboden所說 - 最好使用SELECT CASE。
這也可以用作工作表函數 - =運費(Sheet1!B14)例如。
該函數返回一個VARIANT,以便ELSE語句可以返回錯誤 - 您可能希望將其更改爲CVErr(xlErrNum)以顯示#Num!錯誤代替 - 或者如果您想取消錯誤捕獲,請將返回類型更改爲Double。
你也可以使用CASE> 300

Public Sub Test() 

    Debug.Print freightrate(Range("B14").Value) 

End Sub 

Public Function freightrate(Weight As Double) As Variant 

    Select Case Weight 
     Case 45 
      freightrate = 55 
     Case 46 To 100 
      freightrate = 47 
     Case 100 To 300 
      freightrate = 29.5 
     Case Else 
      freightrate = CVErr(xlErrValue) 
    End Select 


End Function