excel - VBA 代码错误“无效或不合格的参考”
问题描述
我对 vba 编码很陌生。在工作表中,我试图通过检查同时列 J、K、O 中的条件来使用宏列(Q)添加一个附加列。因此,如果某些条件在每一列中传递,我希望在 Q 中输入一个值列对应的行。这是我放在一起的一段代码。
Option Explicit
Sub Button2_Click()
Sheet1.Activate
Dim i As Long
For i = 2 To .Cells(.Rows.Count, "B").End(xlUp).Row
'Check so that we only process non-empty cells
'(just in case there is an empty cell part-way through the data)
If Cells(i, 10).Value = "No" And Cells(i, 15) <= 0 Then
Cells(i, 17) = "Pending with employee"
Else
If Cells(i, 10).Value = "No" And Cells(i, 15) >= 0 And Cells(i, 11) = "No Action Pending" Then
Cells(i, 17) = "Pending with employee"
Else
If Cells(i, 10).Value = "No" And Cells(i, 15) >= 0 And Cells(i, 11) = "Pending With Manager" Then
Cells(i, 17) = "Pending with Manager"
Else
If Cells(i, 10).Value = "Yes" And Cells(i, 15) >= 0 And Cells(i, 11) = "No Action Pending" Then
Cells(i, 17) = "All Done"
'If Not IsEmpty(.Cells(i, "B").Value) Then
' If .Cells(i, "E").Value = "NA" Then'
'ThisWorkbook.Worksheets("CTCto TCC Conversion").Cells(i, "F").Value = "NA" '
End If
End If
End If
End If
Next i
End With
MsgBox "Column Created"
End Sub
它给我一个错误无效或不合格的参考。如果有任何错误需要纠正才能运行代码,请帮助我。
谢谢
解决方案
使用With
语句
- BigBen 已经回答了你的问题。这是一个额外的例子。
- 检查包含
.Cells(i, 15).Value
. 其中一个可能应该删除等号。 - 如果您在一行代码中编写多个条件,即使第一个条件已经
True
(或False
),它们都将被评估,这使得它比在新行中编写每个条件效率低。在实践中,您通常不会感到有什么不同。不过,我无法决定哪一个对您来说更具可读性或可维护性。
Option Explicit
Sub Button2_Click()
With Sheet1
Dim i As Long
For i = 2 To .Cells(.Rows.Count, "B").End(xlUp).Row
If .Cells(i, 10).Value = "No" Then
If .Cells(i, 15).Value <= 0 Then
.Cells(i, 17).Value = "Pending with employee"
Else
If .Cells(i, 11).Value = "No Action Pending" Then
.Cells(i, 17).Value = "Pending with employee"
ElseIf .Cells(i, 11).Value = "Pending With Manager" Then
.Cells(i, 17).Value = "Pending with Manager"
End If
End If
ElseIf .Cells(i, 10).Value = "Yes" Then
If .Cells(i, 15).Value >= 0 Then
If .Cells(i, 11).Value = "No Action Pending" Then
.Cells(i, 17).Value = "All Done"
End If
End If
End If
Next i
End With
MsgBox "Column Created"
End Sub
推荐阅读
- python - 使用 python(Anaconda) 从 SQLite 文件中过滤和提取特定日期
- firebase - Firebase 实时数据库详细使用
- caniuse - 在 img html 中使用视频
- angular - 为什么这个 Angular HttpClient Post 没有同步?
- java - iText 5 - 如何在 Java 中使用 iText 5 设置不同大小的表格单元格
- camera - 如何选择用于阅读非常小的字体字符的镜头
- html - 单击html按钮后执行节点js子进程
- azure-cosmosdb - 在源代码控制和 CI/CD 中维护存储过程、用户定义的函数、索引等的推荐方法
- git - 提交历史中缺少 Git 提交
- php - WordPress mod_rewrite 查询字符串返回 404