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

时间:2019-04-08 03:18:09

标签: excel vba

我在一张纸上有多个表,如何从中收集我感兴趣的数据。 例如,我只需要table1列3和table2列2的数据。 两个表的大小可能会有所不同。我需要将数据收集到数组中以进行下一步处理。

谢谢。

two tables in one sheet

2 个答案:

答案 0 :(得分:0)

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

我建议的是从工作表的顶部循环到最后一行,并在每一行上检查表是否已启动,然后在内部循环中遍历表行,直到表结束(即遇到空行) )。

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

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

答案 1 :(得分: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