【问题标题】:Looping through an Excel File as long as columns are the same只要列相同,就循环遍历 Excel 文件
【发布时间】:2014-07-28 07:43:26
【问题描述】:

我有一个 Excel 文件,其中 A:A 列是名称,B:B 列是相关月份。 同样(A,B):Tom JAN Tom JAN Tom NOV Tom DEC Jack SEP Jack DEC Jack AUG ...

我现在正在尝试遍历此内容。我已经通过使用这个“脚本”循环到列的(未知)结尾来克服第一个障碍。

Sub DoWhile()

Dim i As Long
Dim c As Collection
Set c = New Collection

            
c.Add Cells(1, 1), "Name"
c.Add Cells(1, 2), "Month"
c.Add Cells(1, 3), "Volume"

i = 2
With ActiveSheet
    Do While i <= .Rows.Count
        If .Cells(i, 1) <> "" Then
            c.Add Cells(i, 1), "Name"
            c.Add Cells(i, 2), "Month"
            c.Add Cells(i, 3), "Volume"
            MsgBox c.Item("Name")
            MsgBox c.Item("Month")
            MsgBox c.Item("Volume")
        Else
            Exit Do
        End If
        i = i + 1
    Loop
End With
End Sub

问题: 运行时错误“457”: 此键已与此集合的元素相关联。

似乎我不允许每个键使用多个值。如何绕过这个问题?

用其他语言做这件事会很容易。我将创建一个包含相应列值的列表,并在该列表中循环,只要 list[i-1] == list[i] ...

有人可以帮我吗?

简而言之:

输入:

甲乙

汤姆·简

汤姆·马尔

约翰十一月

约翰十一月

约翰·德克

马克君

马克·简

...

输出应该是一个 excel 表格:

A B C D

汤姆 1 月 - 3 月

约翰 - - -

马克·扬 - - -

等等……

【问题讨论】:

    标签: excel vba


    【解决方案1】:

    我觉得更简单:

    Dim i As Long
    Dim nA(1 To 10000) As String
    Dim nB(1 To 10000) As String
    
    i = 2
    e = 0
    With ActiveSheet
        Do While i <= .Rows.Count
            If .Cells(i, 1) <> "" Then
                If Cells(i - 1, 1) = Cells(i, 1) Then
                    nB(e) = nB(e) & " - " & Cells(i, 2)
                Else
                    e = e + 1
                    nA(e) = Cells(i, 1)
                    nB(e) = Cells(i, 2)
                End If
                MsgBox nA(e) & " : " & nB(e)
            Else
                Exit Do
            End If
            i = i + 1
        Loop
    End With
    

    你不能在一个集合中使用相同的 Key...

    【讨论】:

      【解决方案2】:

      我建议使用类似下面的东西。代码将找到当前区域,然后根据 A1 中的行和前 3 列调整大小。然后我打印到 MsgBox,但如果需要,您可以将它们粘贴到另一个工作表上。

      Dim arr As Variant
      Dim i As Integer
      
      arr = Range("A1").CurrentRegion.Resize(Range("A1").End(xlDown).Row, 3).Value
      
      For i = 1 To UBound(arr)
      
          MsgBox arr(i, 1)
          MsgBox arr(i, 2)
          MsgBox arr(i, 3)
      
      Next i
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多