简体   繁体   English

使用excel vba添加数据透视表

[英]Add pivot table using excel vba

The problem I am facing with adding pivot table to a table is that my source data in the following code.我在向表中添加数据透视表时面临的问题是以下代码中的源数据。 If my reference code keeps changing, how do i format my source data?如果我的参考代码不断变化,我该如何格式化我的源数据?

SourceData: "Test!R35C1:R86C13" keepps changing Sometime my table lies on row 35, sometimes on row 40 or row 100. How do I make this dynamic? SourceData: "Test!R35C1:R86C13" 不断变化 有时我的表位于第 35 行,有时位于第 40 行或第 100 行。我如何使其动态化?

Like this?像这样?

Function table_range()

'return the range of the source table

first_cell = Find_First_Used_Cell()
last_cell = Range_Find_Method(Range(first_cell))

table_range = first_cell + ":" + last_cell

End Function


Function Find_First_Used_Cell()
'modified
'original source: https://www.excelcampus.com/library/find-the-first-used-cell-vba-macro/

'Finds the first non-blank cell in a worksheet.

Dim rFound As Range

    On Error Resume Next
    Set rFound = Cells.Find(What:="*", _
                    After:=Cells(Rows.Count, Columns.Count), _
                    LookAt:=xlPart, _
                    LookIn:=xlFormulas, _
                    SearchOrder:=xlByRows, _
                    SearchDirection:=xlNext, _
                    MatchCase:=False)

    On Error GoTo 0

    If rFound Is Nothing Then
        MsgBox "All cells are blank."
    Else
        'MsgBox "First Cell: " & rFound.Address
        Find_First_Used_Cell = rFound.Address
    End If


End Function


Function Range_Find_Method(rng As Range)
'modified
'original source: https://www.excelcampus.com/library/find-the-first-used-cell-vba-macro/

'Finds the first non-blank cell in a worksheet.

Dim rFound As Range

    On Error Resume Next
    Set rFound = Cells.Find(What:="*", _
                    After:=rng, _
                    LookAt:=xlPart, _
                    LookIn:=xlFormulas, _
                    SearchOrder:=xlByRows, _
                    SearchDirection:=xlPrevious, _
                    MatchCase:=False)

    On Error GoTo 0

    If rFound Is Nothing Then
        MsgBox "All cells are blank."
    Else
        'MsgBox "First Cell: " & rFound.Address
        Range_Find_Method = rFound.Address
    End If
End Function

Now you can simply get the range like this:现在你可以简单地得到这样的范围:

Sub print_my_range()

Set my_range = Range(table_range())

MsgBox (my_range.Address)

End Sub

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM