我正在創建一個程序,可以讓農業生產者輕鬆計算一個罐的體積。我特別希望他們能夠爲他們的坦克輸入多個維度並分別計算每個坦克的體積。尺寸將以逗號分隔,我希望將它們拆分並放入自己的列中。然後,我希望excel能夠獲取每列數據並應用體積公式來獲取圓柱體的體積。我不知道該怎麼做,但我覺得需要循環遍歷每一列,例如第1列的音量,第2列的音量等。下面是代碼。Excel VBA for Loop計算體積
'Seperates values that are seperated by a comma and then puts them in their own column
Public Sub CommaSep()
Selection.TextToColumns _
Destination:=Columns(3), _
DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, _
ConsecutiveDelimiter:=False, _
Tab:=True, _
Semicolon:=False, _
Comma:=False, _
Space:=False, _
Other:=True, _
OtherChar:=","
End Sub
的罐尺寸的代碼是
Public Sub NoInput()
Sheets.Add.Name = "Hidden Information"
Worksheets(2).Activate
Dim tankCount As Integer
tankCount = Application.InputBox("Enter the Number of Tanks that will be in the Secondary Containment", "Known Tank Quantity", 1)
If tankCount = False Then
Call DeleteSheets
Exit Sub
Else
tankTotal = tankCount
End If
Dim knownVol As Variant
knownVol = Application.InputBox("Enter the Known Volume of the Tank in Gallons. If volume is not known then enter 0", "Known Tank Volume", 0)
If knownVol = "" Then
Call DeleteSheets
Exit Sub
ElseIf knownVol > 0 Then
Application.Worksheets(1).Range("A6").Value = "Known Tank Volume"
Application.Worksheets(1).Range("B6").Value = knownVol
' Application.Worksheets(2).Range("A6").Value = "Known Tank Volume"
' Application.Worksheets(2).Range("B6").Value = knownVol
' Call SPCCSizedSecondary
' Exit Sub
Else
End If
Dim diameter As Variant
diameter = Application.InputBox("Enter the Diameter of the Tanks in feet seperated by commas", "Diameter", 1)
If diameter = False Then
Call DeleteSheets
Exit Sub
Else
Application.Worksheets(1).Range("A4").Value = "Diameter"
Application.Worksheets(1).Range("B4").Value = diameter
End If
Dim length As Variant
length = Application.InputBox("Enter the Length of the Tanks in feet seperated by commas", "Length", 1)
If length = False Then
Call DeleteSheets
Exit Sub
Else
Application.Worksheets(1).Range("A5").Value = "Length"
Application.Worksheets(1).Range("B5").Value = length
End If
'Dim knownVol As Variant
'knownVol = Application.InputBox("Enter the Known Volume(s) of the Tank in Gallons seperated by commas. If volume is not known then enter 0", "Known Tank Volume", 0)
'If knownVol = False Then
' Call DeleteSheets
' Exit Sub
'Else
' Application.Worksheets(1).Range("A6").Value = "Known Tank Volume"
' Application.Worksheets(1).Range("B6").Value = knownVol
'End If
Columns(1).AutoFit
Columns(2).AutoFit
'Call DeleteSheets
End Sub
感謝您的回覆!我想由於我對整個Excel VBA編程的新穎性,我不太清楚如何在我的例程中實現一個函數。我只習慣使用Sub而不是Function。你可以給我一個如何在宏內使用它的想法嗎? – JuliusDariusBelosarius
@JuliusDariusBelosarius我將添加一個編輯來闡明如何將所有內容放在一起。要使用該功能,您只需將其複製並粘貼到您的Sub下;因此將整個函數從Function複製到End Function,並直接粘貼到最後一個End Sub下面。然後,你可以在你的Sub中引用這個函數,比如'calc_cylinder_volume(dblDiameter(i),dblLength(i))' – Etheur
只需添加你可以使用:Application.WorksheetFunction。Pi()獲得Pi –