我是VBA的新手,我尝试插入VLOOKUP
函数。
我从网页上获取数据,经过一些自动过滤和自动删除后,数据缩小到较小的尺寸。但由于它是动态数据,因此最后一行总是会改变。
我的数据是这样的:
A B C
FleetType MSN Registration
我已填写注册(C
),并希望找到列在不同表格中的车队类型。
我尝试使用FormulaR1C1
插入公式,但最终得到1004消息。我也尝试使用Application.VLookup
,也获得了1004消息。
由于我无法完成这项工作,因为我知道注册的前两个字母给出了关于舰队类型的线索,我已经设置了一个嵌套的IF
函数并尝试插入它;没有运气也。
这是sub
我试图让它运行(我没有删除我试过的那些):
Sub formuller()
Worksheets("Data").Select
Worksheets("Data").Activate
'range("A1:A600").Formula = "=IF(LEFT(D2;2)="JK";"Boeing";IF(LEFT(D2;2)="JG";"Boeing";IF(LEFT(D2;2)="JF";"Boeing";IF(LEFT(D2;2)="JH";"Boeing";IF(LEFT(D2;2)="JV";"Boeing";IF(LEFT(D2;2)="JJ";"Boeing";IF(LEFT(D2;2)="JY";"Boeing";IF(LEFT(D2;2)="LJ";"Boeing";"Airbus"))))))))"
On Error Resume Next
Range("A1:A2").FormulaR1C1 = "=IF(LEFT(RC[3];2)=""JK"";""Boeing"";IF(LEFT(RC[3];2)=""JG"";""Boeing"";IF(LEFT(RC[3];2)=""JF"";""Boeing"";IF(LEFT(RC[3];2)=""JH"";""Boeing"";IF(LEFT(RC[3];2)=""JV"";""Boeing"";IF(LEFT(RC[3];2)=""JJ"";""Boeing"";IF(LEFT(RC[3];2)=""JY"";""Boeing"";IF(LEFT(RC[3];2)=""LJ"";""Boeing"";""Airbus""))))))))"
On Error GoTo 0
'Worksheets("Data").Range("A1:A600").FormulaR1C1 = "=VLOOKUP(RC[3];Filo!R1C1:R309C3;3;FALSE)"
这有什么办法吗?我要问的只是在VBA项目中使用旧的VLookup
。
答案 0 :(得分:0)
您可以将WorksheetFunction.VLookup
用于好的VLookup
。
但另外,您可以将此宏用于您的porpuse。解释在评论中。
Option Explicit
Sub FindFleetType()
Const Boeing As String = "Boeing"
Const Airbus As String = "Airbus"
Dim MySheet As Worksheet
Dim MyRange, c As Range
Dim MyInt, LastRow As Integer
Dim MyStr, MyArray(7) As String
'filling string array
MyArray(0) = "JK"
MyArray(1) = "JG"
MyArray(2) = "JF"
MyArray(3) = "JH"
MyArray(4) = "JV"
MyArray(5) = "JJ"
MyArray(6) = "JY"
MyArray(7) = "LJ"
'defining worksheet
Set MySheet = ThisWorkbook.Worksheets("Data")
'finding lastrow has data on columnn C
'so you don't have to change the range manually every time
With MySheet
LastRow = .Range("C" & .Rows.Count).End(xlUp).Row
End With
'defining range to be filled
Set MyRange = ThisWorkbook.ActiveSheet.Range("A2:A" & LastRow)
'iterating each cell on defined range
For Each c In MyRange
MyStr = Left(c.Offset(0, 2).Value2, 2) 'get first two letters of "Registration" column C
'control if your array contains your string
If ContainString(MyStr, MyArray) Then
c.Value2 = Boeing
Else
c.Value2 = Airbus
End If
Next
End Sub
Private Function ContainString(ByVal StringToBeFound As String, StringArray As Variant) As Boolean
ContainString = (UBound(Filter(StringArray, StringToBeFound)) > -1)
End Function