我在下面的代码中使用了 vlookup,但它导致类型不匹配。我已经更改了所有惯例,制作了变量变体,将其更改为应用程序而不是工作表函数,但我仍然收到错误。谁能发现我做错了什么吗?
Sub createSQL()
Dim Br As Range
Dim Branch As Variant
Dim Rep As Range
Dim Report As Variant
Dim RowNo As Long
Dim SQLCode As Range
Dim SQLCode2 As String
Dim SQLCode3 As String
Dim BranchID As Long
Dim Exception As String
Dim ExCode As Variant
Set Br = Sheets("sheet3").Range("D2:D5")
SQLCode3 = Sheets("Issues").Range("F2")
SQLCode2 = Sheets("Issues").Range("F3")
For Each Branch In Br
RowNo = Branch.Row
Set SQLCode = Sheets("Sheet3").Range("L" & RowNo)
BranchID = Sheets("Sheet3").Range("C" & RowNo)
SQLCode = SQLCode3 & BranchID & SQLCode2
Set Rep = Sheets("Sheet3").Range("I" & RowNo & ":K" & RowNo).Columns
For Each Report In Rep
If Report <> "" Then
SQLCode = SQLCode & Report
Else
SQLCode = ""
End If
ExCode = Sheets("Sheet3").Range("C" & RowNo) & Sheets("Sheet3").Range("D" & RowNo) & Cells(1, Report.Column)
Exception = Application.VLookup(ExCode, Sheets("Exceptions").Range("D2:E2"), 2, False)
SQLCode = SQLCode & Exception & " Union All "
Next Report
SQLCode = Left(SQLCode, Len(SQLCode) - 10)
Next Branch
End Sub
最佳答案
第一个问题是它应该是 Application.WorksheetFunction.VLookup
。
第二个是 VLookUp
可能会返回错误,并且不会进入任何字符串,因此您必须在将其分配给 Exception
之前对其进行测试。
我只是倾向于这一点,但您正在尝试对仅一行进行垂直查找...这肯定是错误的根源,因为您不会在一排中找到很多不同的东西...
如果将 ExCode
和 Exception
设置为字符串,则可能适用于以下代码:
Dim LookUp_Range As Range
Set LookUp_Range = Sheets("Exceptions").Range("D2:E10")
If IsError(Application.WorksheetFunction.VLookup(ExCode, LookUp_Range, 2, False)) Then
Exception = "Error"
Else
Exception = Application.WorksheetFunction.VLookup(ExCode, LookUp_Range, 2, False)
End If
所以你的整个代码将如下所示:
Sub createSQL()
Dim Br As Range
Dim Branch As Variant
Dim Rep As Range
Dim Report As Variant
Dim RowNo As Long
Dim SQLCode As Range
Dim SQLCode2 As String
Dim SQLCode3 As String
Dim BranchID As Long
Dim Exception As String
Dim ExCode As String
Dim LookUp_Range As Range
Set Br = Sheets("sheet3").Range("D2:D5")
SQLCode3 = Sheets("Issues").Range("F2")
SQLCode2 = Sheets("Issues").Range("F3")
Set LookUp_Range = Sheets("Exceptions").Range("D2:E10")
With Sheets("Sheet3")
For Each Branch In Br
RowNo = Branch.Row
Set SQLCode = .Range("L" & RowNo)
BranchID = .Range("C" & RowNo)
SQLCode = SQLCode3 & BranchID & SQLCode2
Set Rep = .Range("I" & RowNo & ":K" & RowNo).Columns
For Each Report In Rep
If Report <> "" Then
SQLCode = SQLCode & Report
Else
SQLCode = ""
End If
ExCode = .Range("C" & RowNo) & .Range("D" & RowNo) & Cells(1, Report.Column)
If IsError(Application.WorksheetFunction.VLookup(ExCode, LookUp_Range, 2, False)) Then
Exception = "Error"
Else
Exception = Application.WorksheetFunction.VLookup(ExCode, LookUp_Range, 2, False)
'Concatenate only if there is a match!
SQLCode = SQLCode & Exception & " Union All "
End If
Next Report
SQLCode = Left(SQLCode, Len(SQLCode) - 10)
Next Branch
End With
End Sub
关于vba Vlookup类型不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33628782/