以下代码遇到一些问题。我在启动第二个for循环时遇到了应用程序定义或对象定义的错误。第二个循环范围的格式似乎是导致问题的原因。删除Sheets()对象可以消除错误,但是脚本会从错误的工作表中读取,并且不会返回任何数据。
此代码的目标是循环遍历垂直数据数组,然后如果找到与下拉列表中的选择匹配,则循环遍历水平数据数组并返回颜色更改,如果它找到'是'价值。
If Not Intersect(Target, Range("countryProductCell")) Is Nothing Then
lastcolumn = ActiveSheet.UsedRange.Column - 1 + ActiveSheet.UsedRange.Columns.Count
Dim cellRow As Integer
cellRow = Target.Row
Dim defaultCellColumn As Integer
defaultCellColumn = 4
i = 5
j = 1
k = 1
If Not Cells(cellRow, defaultCellColumn).Value = "(Select Title)" Then
For Each countryCell In Range(Cells(cellRow, defaultCellColumn + 1), Cells(cellRow, lastcolumn))
If countryCell.Value = "Use Default" Then
countryCell.Interior.ColorIndex = 3
End If
Next
For Each nameCell In Sheets("Active Product Catalog").Range("ProductNames")
If nameCell.Value = Cells(cellRow, defaultCellColumn).Value Then
'Error on the line below!
For Each purchaseableCell In Sheets("Active Product Catalog").Range(Cells(nameCell.Row, 10), Cells(nameCell.Row, 27))
If purchaseableCell.Value = "Yes" Then
'If Purchaseable, Change Color
Sheets("Home Template").Cells(cellRow, defaultCellColumn + j).Interior.ColorIndex = 35
End If
j = j + 1
Next
End If
k = k + 1
Next
ElseIf Cells(cellRow, defaultCellColumn).Value = "(Select Title)" Then
If Target.Value = "(Select Title)" Then
Target.Interior.Color = Cells(Target.Row, Target.Column - 1).Interior.Color
For Each countryCell In Range(Cells(cellRow, defaultCellColumn + 1), Cells(cellRow, lastcolumn))
If countryCell.Value = "Use Default" Then
countryCell.Interior.ColorIndex = 2
End If
i = i + 1
Next
ElseIf Target.Value = "Use Default" Then
Target.Interior.ColorIndex = 2
ElseIf Application.VLookup(ActiveSheet.Cells(cellRow, Target.Column), Sheets("Active Product Catalog").Range("E:AK"), Target.Column, False) = "Yes" Then
Target.Interior.ColorIndex = 35
ElseIf Not Application.VLookup(ActiveSheet.Cells(cellRow, Target.Column), Sheets("Active Product Catalog").Range("E:AK"), Target.Column, False) = "Yes" Then
Target.Interior.ColorIndex = 3
End If
End If
End If
答案 0 :(得分:5)
您需要在代码中限定Cells引用。它失败的原因是您正在使用来自一个工作表(活动工作表)的两个Cell引用,并要求VBA在另一个工作表(Active Product Catalog)中定义范围。尝试这样的事情:
Sheets("Active Product Catalog").Range(Sheets("Active Product Catalog").Cells(nameCell.Row, 10), Sheets("Active Product Catalog").Cells(nameCell.Row, 27))
如果您创建工作表对象或使用With语句,您可能会发现它更容易阅读。