表格操作系列——利用字段名获取表格中对应列的数据

表格操作系列

一、利用字段名获取表格中对应列的数据

在利用VBA操作表格时,经常需要提取其中的某些数据,为了能够轻松完成操作和,而不用每次都写复杂的代码,编制了下面的函数,支持单列的字段名和列号,以及多列的字段名来获取相应的数据,可以方便的使用。

函数代码

Public Function GetSheetDatas(Fie, Optional WithFie As Boolean = False, Optional Sh As String = "ActiveSheet")
Dim Rng As Range
Dim Lr As Integer
Dim sp() As String
Dim i As Integer
Dim j As Integer
Dim Arr() As String
Dim dic As Object
Set dic = CreateObject("Scripting.Dictionary")
dic.CompareMode = vbTextCompare        '采用文本的比较方式,不分大小写

If Sh = "ActiveSheet" Then Sh = ActiveSheet.Name
With Sheets(Sh)
    If InStr(Fie, ",") Then '当字段名为多列时
        sp = Split(Fie, ",")
        For i = 0 To UBound(sp)
            Set Rng = .Range("1:1").Find(sp(i), lookat:=xlWhole)
            If Not Rng Is Nothing Then dic(sp(i)) = Rng.Column  '建立字段对应列号字典
        Next
        Set Rng = .Range("1:1").Find(sp(0), lookat:=xlWhole)
        If Not Rng Is Nothing Then Fie = Rng.Column
        Lr = .Cells(65536, Fie).End(xlUp).Row   '使用第一个字段取得数据行数
        If WithFie Then '判断是否需要带字段名返回
            ReDim Arr(Lr - 1, UBound(sp))
            For j = 0 To UBound(sp)
                Arr(0, j) = sp(j)
            Next
        Else
            ReDim Arr(Lr - 2, UBound(sp))
        End If
        For i = 2 To Lr '获取字段对应的数据
            For j = 0 To UBound(sp)
                Arr(i - 2 - WithFie, j) = .Cells(i, dic(sp(j)))
            Next
        Next
        GetSheetDatas = Arr
    Else
        If Not IsNumeric(Fie) Then  '判断所给字段名是否为数字,如果是数字,直接取数字对应的列
            Set Rng = .Range("1:1").Find(Fie, lookat:=xlWhole)
            If Not Rng Is Nothing Then Fie = Rng.Column
        End If
        Lr = .Cells(65536, Fie).End(xlUp).Row
        If Lr > 1 Then
            GetSheetDatas = .Cells(1, Fie).Offset(1 - -WithFie).Resize(Lr - 1 - WithFie).Value
        Else
            GetSheetDatas = False
        End If
    End If
End With
End Function

以上内容还可以增加条件判断,从表格中取出符合条件要求的数据来,这个留给大家探索了。

表格操作系列未完,待续!

——专注办公软件的二次开发及培训,你有问题,我有思路!
——微博、微信、CSDN同号:w_dexu
——转载请注明出处!

表格操作系列——利用字段名获取表格中对应列的数据_第1张图片扫码加微信

你可能感兴趣的:(函数,VBA,表格,vba,excel,wps)