vba - VBA 编译错误 1004
问题描述
我是 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
解决方案
进行此编译需要进行大量更改。当您尝试运行时,添加Option Explicit
将告诉您所有编译错误的确切位置。一旦解决了这些问题,就可以开始调试运行时错误(或逻辑错误)。
1)使用时,您可以通过索引或“字母”(或)Cells
引用列
2)您有一些未定义的变量
3)不需要 2 个语句,只需将它们组合使用
4)您可以摆脱方法和在一个语句中使用您的两个标准 ( )
5) 确保您使用了正确的变量。每个变量对它可以和不能保持什么都有限制。例如,不能容纳 4.2(您的变量将被默默地转换为 4 以匹配您声明的变量)
6)您需要使用工作表限定您的实例。Cells(2, 1)
Cells(2, "A")
If
ElseIf
Select Case
If
If MAN = 1 And ItemClass = "AK" Then
Integer
WPA
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 捕捉到更多的建议
5 和 6 从其他人的有用评论中修改(Craner & Guindon)
推荐阅读
- composer-php - Drupal Composer 需求无法解析为一组可安装的包
- python - sudo -H pip install 和 pip --user install 的区别
- c# - ASP.NET Core 2.1 Web API - ConfigurationManager.ConnectionStrings 返回 null
- swift - Eureka - DateRow 加载日期而不更改其当前值
- java - 从 Oracle JDK 迁移到 OpenJDK
- python - 嵌套的 dict 键被覆盖
- javascript - 本地存储中 >100Mb 的数据
- javascript - 如果有新请求则取消请求(承诺)
- git - Git合并忽略空行
- android - 如何在使用导航架构时将数据传递给第一个片段?