从Excel中的表中收集感兴趣的数据

问题描述 投票:0回答:2

我在一张表中有多个表,如何从他们那里收集我感兴趣的数据。例如,我只需要table1第3列和第2列第2列的数据。两个表的大小可能是变量的。我需要将数据收集到数组中以进行下一步处理。

谢谢。

excel vba
2个回答
0
投票

您需要找到一种方法来限制VBA中的表,即知道它们在哪一行开始以及它们包含多少行。由于表格可以出现在具有变量维度的工作表中的任何位置,因此没有直接的方法来提取其数据。

我建议循环从工作表的顶部到lastrow,并在每一行检查表是否开始,然后在内部循环中迭代表行直到表结束(即遇到空行)。

代码可能看起来与此类似(未经测试):

Dim LastRow as Long, i as Long, k as Long
Dim sht as Worksheet
LastRow = sht.Cells(sht.Rows.Count, "A").End(xlUp).Row 'Assuming the tables start in column A

For i=1 to LastRow
    If (sht.Range("A" & i) <> "" Then 'table is encountered
        k = i
        Do While sht.Range("A" & k) <> ""
             ... 'Get data from specific column
             k = k + 1
        Loop        
    End if
    i = k
Next i

0
投票

试试这个(必要的评论在代码中):

Option Explicit
Sub CollectData()
    Dim table1Address As String, table2Address As String
    ' here you specify cells that are at the start of a column
    table1Address = "B2"
    table2Address = "C7"

    Dim firstCell As Range, lastCell As Range
    Dim table1Data, table2Data As Variant
    ' determine last cell in column and read whole column at once to an array variable
    Set firstCell = Range(table1Address)
    Set lastCell = Range(table1Address).End(xlDown)
    table1Data = Range(firstCell, lastCell).Value2

    Set firstCell = Range(table2Address)
    Set lastCell = Range(table2Address).End(xlDown)
    table2Data = Range(firstCell, lastCell).Value2

End Sub
© www.soinside.com 2019 - 2024. All rights reserved.