在VBA中获取数组的第N个索引

时间:2019-05-06 18:50:47

标签: excel vba

我在VBA中是菜鸟,无法找到在给定索引处获取数组元素的方法...但是,这对您来说可能很容易。

我有一个Excel文件,其中包含“电子邮件”和“类别”两列,并且我想过滤出给定类别的所有电子邮件。

到目前为止,我得到了以下代码:

Sub filterEmails()

    Dim tbl As ListObject
    Dim emails As Variant
    Dim email As String
    Dim categories As Variant
    Dim category As String
    Dim i As Integer

    Set tbl = ActiveWorkbook.Worksheets("Feuil1").ListObjects("Tableau1")
    emails = tbl.ListColumns("EMAILS").DataBodyRange.Value
    categories = tbl.ListColumns("SERVICES").DataBodyRange.Value

    i = 1
    For Each email In emails

        category = ???

        If category = "some service" Then
            MsgBox email
        End If

        i = i + 1
    Next email

End Sub

我尝试了多种方法来从Categories数组中获取第i个项目,例如categories(i),但没有成功。可能是因为我无法用正确的类型初始化变量。

2 个答案:

答案 0 :(得分:3)

我会这样:

Sub filterEmails()

    Dim tbl As ListObject
    Dim emails As Variant
    Dim email As String
    Dim categories As Variant
    Dim category As String
    Dim i As Long '<< always best to prefer Long over Integer

    Set tbl = ActiveWorkbook.Worksheets("Feuil1").ListObjects("Tableau1")

    'Both "emails" and "categories" will be 2-D arrays
    emails = tbl.ListColumns("EMAILS").DataBodyRange.Value
    categories = tbl.ListColumns("SERVICES").DataBodyRange.Value


    For i = lbound(emails,1) to ubound(emails, 1) 

        category = categories(i, 1)

        If category = "some service" Then
            MsgBox email
        End If
    Next i

End Sub

答案 1 :(得分:1)

这是您的代码,做了一些修改,现在应该可以工作了:

    Option Explicit

    Sub filterEmails()

    Dim tbl As ListObject
    Dim emails As Variant
    Dim email As Variant
    Dim categories As Variant
    Dim category As String
    Dim i As Integer

    Set tbl = ActiveWorkbook.Worksheets("Feuil1").ListObjects("Tableau1")
    emails = tbl.ListColumns("EMAILS").DataBodyRange.Value
    categories = Application.Transpose(tbl.ListColumns("SERVICES").DataBodyRange.Value)

    i = 1
    For Each email In emails

        category = categories(i)

        If category = "some service" Then
            MsgBox email
        End If

        i = i + 1
    Next email

End Sub

评论:

categories(i)

该命令将不起作用,因为categories是2维数组,我使用Application.transpose命令将其存储为1维数组。