Vlookup和Loop的数组

时间:2017-03-22 23:13:56

标签: vba

我是VBA的新手,你能帮我吗? 我想创建一个包含3个值的数组:2维

1 = Data
2 = Functions
3 = Other

然后在Excel中,如果这三个数字中的一个,请查看For Each或For Next to the Array并检索字符串,如 for i = 1 to 20, if cells(i,1).Value = 1 or 2 or 3然后分配字符串..

谢谢你的帮助

4 个答案:

答案 0 :(得分:0)

您可以从工作表中选取一个二维数组,然后使用Dim arr, m arr = Range("G4:H6").Value m = Application.VLookup(Range("G9"), arr, 2, False) Range("H9") = IIf(IsError(m), "???", m)

IsError(m)

如果没有匹配,则True将为Dim arr(1 to 3, 1 to 2), m arr(1, 1) = 1 arr(1, 2) = "One" arr(2, 1) = 2 arr(2, 2) = "Two" arr(3, 1) = 3 arr(3, 2) = "Three" m = Application.VLookup(Range("G9"), arr, 2, False) Range("H9") = IIf(IsError(m), "???", m)

编辑:在代码中加载数组

@{u}..

答案 1 :(得分:0)

很抱歉...... 我用Loop修改了一点,它有效,谢谢

    Sub test()
Dim arr(1 To 3, 1 To 2), m

arr(1, 1) = 1: arr(1, 2) = "One"
arr(2, 1) = 2: arr(2, 2) = "Two"
arr(3, 1) = 3: arr(3, 2) = "Three"
For Each m In Range("C9:C12")
m.Value = Application.VLookup(m, arr, 2, False)

m = IIf(IsError(m), "???", m)
Next
End Sub

答案 2 :(得分:0)

站在您的数组结构中,您可以按照以下方式简化代码:

Sub test()
    Dim arr As Variant
    Dim m As Range

    arr = Array("One", "Two", "Three")

    On Error Resume Next '<--| prevent possible out-of-array values to stop the code
    With Range("C9:C12") '<--| reference your relevant range
        For Each m In .Cells '<--| loop through its cells
            m.Value = arr(m - 1) '<--| an m.Value of 1 would point at the 0th (i.e.: the "first") position of the array 
        Next
        .SpecialCells(xlCellTypeConstants, xlNumbers).Value = "???" '<--| substitute "survived" numbers (i.e. out of array indexes) with "???"
    End With
End Sub

答案 3 :(得分:0)

基于此代码,如何添加一行 例如

1 = "One" = "OK"
2 = "Two" = "OK"
3 = "Three" = "Not OK"

基本上:1和2有2维和1个超维

            Sub test()
Dim arr(1 To 3, 1 To 2), m

arr(1, 1) = 1: arr(1, 2) = "One"
arr(2, 1) = 2: arr(2, 2) = "Two"
arr(3, 1) = 3: arr(3, 2) = "Three"
For Each m In Range("C9:C12")
m.Value = Application.VLookup(m, arr, 2, False)

m = IIf(IsError(m), "???", m)
Next
End Sub