我是VBA的新手,所以我很抱歉如果错误很明显,但是在以下代码中出现运行时错误,我不明白为什么,我唯一的想法是在第一个for循环上使用了StepCount变量获取它的值在for循环本身内分配,我之前看不到放置它的方法,因为它基于用于for循环的x?不知道如何以一种可行的方式链接它们
Sub EST()
'Constants
Dim W2P As Integer
W2P = 4.2
Dim WPA As Integer
WPA = 20
Dim AKPA As Integer
AKPA = 5
Dim AKMan As Integer
AKMan = 10
Dim AKP As Integer
AKP = 4
'looping through orders
For x = 2 To 700 Step StepCount
Dim OrderNum As Integer
OrderNum = Cells(x, A).Value
'each order has sub rows loop steps unique amount each cycle
StepCount = Cells(x, BB).Value
'each order has unique number of these sub rows
Dim LineNum As Integer
LineNum = Cells(x, BA).Value
Dim Sum As Integer
Sum = 0
'for loop supossed to perform function on each orders data
For i = (x + 1) To (LineNum)
Dim Ti As Integer
Ti = 0
Dim ItemClass As String
ItemClass = Cells((x + 1), s).Value
Dim QTY As Integer
QTY = Cells((x + 1), P).Value
Dim MAN As Integer
MAN = Cells((x + 1), Q).Value
Select Case ItemClass
'Case AF
Case AK
If MAN = 1 Then
Ti = (AKP + AKMan * QTY + AKPA * QTY)
End If
If MAN = 0 Then
Ti = (AKP + AKPA * QTY)
End If
End Select
Sum = Sum + Ti
Set Cells(x, AX).Value = Sum
Next
Next x
End Sub
答案 0 :(得分:3)
进行此编译需要很多更改。添加Option Explicit
会准确告诉您所有试图运行时所有编译错误的位置。解决这些问题后,就可以开始调试运行时错误(或逻辑错误)。
1)使用Cells
时,您可以按索引或“字母”(Cells(2, 1)
或Cells(2, "A")
)引用列
2)您有一些未定义的变量
3)不需要2条If
语句,只需使用ElseIf
组合它们
4)您可以摆脱Select Case
方法,并在一个If
语句(If MAN = 1 And ItemClass = "AK" Then
)中使用两个条件。
5)确保使用正确的变量。每个变量在其可以保留和不能保留的内容上都有限制。例如,Integer
不能容纳4.2(您的变量WPA
将被静默转换为4以匹配您声明的变量)
6)您需要使用工作表来限定Cells
的实例。
这可能仍然会产生运行时错误,但现在会编译。
Option Explicit
Sub EST()
Dim WPA as Double, AKPA as Integer, AKMan as Integer, AKP As Integer
Dim W2P As Variant
W2P = 4.2
WPA = 20
AKPA = 5
AKMan = 10
AKP = 4
Dim x as Long, i as Long, StepCount As Long
Dim OrderNum, LineNum, Sum, Ti, QTY, MAN As Variant
Dim ItemClass As String
For x = 2 To 700 Step StepCount
StepCount = Cells(x, "BB").Value
OrderNum = Cells(x, "A").Value
LineNum = Cells(x, "BA").Value
Sum = 0
For i = (x + 1) To (LineNum)
Ti = 0
ItemClass = Cells((x + 1), "S").Value
QTY = Cells((x + 1), "P").Value
MAN = Cells((x + 1), "Q").Value
If MAN = 1 And ItemClass = "AK" Then
Ti = (AKP + AKMan * QTY + AKPA * QTY)
ElseIf MAN = 0 And ItemClass = "AK" Then
Ti = (AKP + AKPA * QTY)
End If
Sum = Sum + Ti
Cells(x, "AX").Value = Sum
Next i
Next x
End Sub
1和2将被Option Explicit
捕获
3和4是更多建议
其他人(Craner和Guindon)的有用评论对5和6进行了修正