我试图创建一个代码,让我可以检查A列和C列是否匹配" Car"和"红"。如果是的话,我想用现有的DicoRedCar
填充汽车的品牌作为项目,而Price as Key就是我的代码:
Sub Dicofill()
Dim DicoRedCar As Object
Set DicoRedCar = CreateObject("Scripting.Dictionary")
Dim Startcell As Range
Set Startcell = Data.Range("A1")
i = i + 1
If Startcell.Offset(i, 0).Value = "Car" And Startcell.Offset(i, 2).Value = "Red" Then
DicoRedCar.Add Startcell.Offset(i, 0).Value, Startcell.Offset(i, 1).Value
End If
End Sub
第1列是车型,第2列车品牌,第3列车颜色,第6列车价。
但它不能为Dico提供食物。我知道在A24的范围内我出现了一辆红色汽车,但没有任何反应。我试着用MsgBox检查Then语句,但它什么都没给我。我试过这个但没有发生任何事情:
If Startcell.Offset(i, 0).Value = "Car" And Startcell.Offset(i, 2).Value = "Red" Then
Msgbox("found a Red Car")
End If
所以我认为封锁点首先来自我的"如果......那么"陈述
答案 0 :(得分:0)
这可能会让你开始:
Sub Dicofill()
Dim DicoRedCar As Object
Dim Startcell As Range
Dim myCell As Range
Set DicoRedCar = CreateObject("Scripting.Dictionary")
Set Startcell = Range("A1")
For Each myCell In Range("A1:A10")
If myCell.Offset(0, 1) = "Car" And myCell.Offset(0, 2) = "Red" Then
'it is a good idea to check whether the key exists before adding it:
DicoRedCar.Add myCell.Offset(0, 1), myCell.Offset(0, 4)
End If
Next myCell
End Sub
它遍历范围(" A1:A10")并检查列B
是否为" Car"和#34;红色"列C
。如果找到它们,则将列B
添加到字典DicoRedCar
作为键,列E
就是值。
下一步,考虑在添加密钥之前检查字典中是否存在密钥,因为它会给您一个错误。这是怎么做的:
dict.Exists(Key)
e.g. If DicoRedCar.Exists(myCell.Offset(0,1)) Then
答案 1 :(得分:0)
假设Data
是对工作表的引用..以下将扫描A列并在到达第一个空单元格时停止:
Sub Dicofill()
Dim DicoRedCar As Object
Set DicoRedCar = CreateObject("Scripting.Dictionary")
Dim Startcell As Range
Set Startcell = Data.Range("A1")
Do Until Startcell.Offset(i + 1, 0).Value = ""
i = i + 1
If Startcell.Offset(i, 0).Value = "Car" And Startcell.Offset(i, 2).Value = "Red" Then
DicoRedCar.Add Startcell.Offset(i, 0).Value, Startcell.Offset(i, 1).Value
End If
Loop
End Sub