【问题标题】:Get the Nth index of an array in VBA获取VBA中数组的第N个索引
【发布时间】:2019-05-07 03:18:40
【问题描述】:

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

我有一个包含 2 列“电子邮件”和“类别”的 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

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

【问题讨论】:

    标签: excel vba


    【解决方案1】:

    我会这样做:

    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
    

    【讨论】:

      【解决方案2】:

      这是你的代码,稍作改动,现在应该可以工作了:

          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 是一个二维数组,我使用Application.transpose 命令将它存储为一维数组。

      【讨论】:

        猜你喜欢
        • 2022-01-20
        • 2018-06-06
        • 1970-01-01
        • 1970-01-01
        • 2013-07-11
        • 2011-02-16
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多