Hi试图检查Y列中的每个单元格是否来自另一个工作表的列表。vlookup函数的结果总是"false“。我不知道为什么。请指教
Sub CheckDropDown()
Dim MyStringVar As Variant, i As Integer
Dim Lookup_Range As Range, lastRow As Integer, ws As Worksheet
Set Lookup_Range = Worksheets("Lists").Range("C1:C21")
lastRow = Cells.Find("*", [A1], , , xlByRows, xlPrevious).row
For i = 2 To lastRow
On Error Resume Next
'MyStringVar = ActiveCell.FormulaR1C1 = "=VLOOKUP(Cells(i,25),Lists!C[-25],1)"
MyStringVar = ActiveCell.Formula = "VLookup(Cells(i, 25).value, Lookup_Range, 1, False)"
On Error GoTo 0
Select Case Cells(i, 25).value
Case IsEmpty(MyStringVar)
' do nothing
Case Is = MyStringVar
Case Is <> MyStringVar
ActiveSheet.Cells(i, 25).Interior.Color = RGB(255, 255, 5)
End Select
Next i
End Sub
发布于 2016-01-17 14:03:33
我的期望是,您得到了这个意外的结果,因为您没有在ActiveCell中编写有效的公式。一个有效的公式是
=VLOOKUP(Y2, 'Lists'!C1:C21, 1, FALSE)
因此,以这样的方式创建代码,这就是引号之间的内容"“。
如果你把一个有效的公式,也就是你试着在你的excel表格上写的公式,那么它就会起作用。现在,您正在将excel公式与编程语言混合在界面中。
所以就像这样:
Dim myFormula As String
myFormula = "=VLOOKUP("
Dim columnLetter As String
columnLetter = "Y"
Dim tmpFormula As String
For i = 2 to x
tmpFormula = myFormula & columnLetter & i & ", 'lists'!C1:C25, 1, FALSE)"
.. test formula .. etc.
Next i
成功
ps。如果你需要公式前面的“=”,就不要再记了,所以试试这个。
发布于 2016-01-17 16:15:06
我不喜欢将公式和代码组合在一起,因为您只需要解决其中的一个问题,所以我建议您使用纯代码来检查以这段代码为基础的值。
Sub CheckDropDown()
Dim MyStringVar As Variant, i As Integer
Dim Lookup_Range, cel As Range, lastRow As Integer, check As Boolean
Set Lookup_Range = Worksheets("Lists").Range("C1:C21")
lastRow = ActiveSheet.Cells(ActiveSheet.Rows.Count, "A").End(xlUp).Row
For i = 2 To lastRow
For Each cel In Lookup_Range
If ActiveSheet.Cells(i, 25) = cel.Value Then
check = True: Exit For
Else
check = False
End If
Next
If check Then
'The cell is on the lookupRange
Else
'The cell is NOT on the lookupRange
ActiveSheet.Cells(i, 25).Interior.Color = RGB(255, 255, 5)
End If
Next i
End Sub
https://stackoverflow.com/questions/34844074
复制