簡體   English   中英

使用excel vba添加數據透視表

[英]Add pivot table using excel vba

我在向表中添加數據透視表時面臨的問題是以下代碼中的源數據。 如果我的參考代碼不斷變化,我該如何格式化我的源數據?

SourceData: "Test!R35C1:R86C13" 不斷變化 有時我的表位於第 35 行,有時位於第 40 行或第 100 行。我如何使其動態化?

像這樣?

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

現在你可以簡單地得到這樣的范圍:

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