动态修改表大小

时间:2015-10-05 07:58:03

标签: excel vba

我编写了一个代码,在过滤一些行之后从另一个表中导入一个表。我的问题是,当我超过表中我在该表中的行数时,它超出了表。现在,我想知道是否有办法用行数动态修改表的大小。

Public Sub refresh()

Dim ws1 As Worksheet, ws2 As Worksheet, lr1 As Long, lRow As Long
    Set ws1 = ThisWorkbook.Worksheets("Scénarios de menace")
    Set ws2 = ThisWorkbook.Worksheets("Analyse de risque")
    Application.Calculation = xlCalculationAutomatic
    ws2.Range("B6:N" & ws2.Cells(ws2.Rows.Count, 2).End(xlUp).Row).ClearContents 
    lr1 = ws1.Cells(ws1.Rows.Count, 2).End(xlUp).Row
        ws1.Range("A1:A" & lr1).AutoFilter Field:=1, Criteria1:="x"
        ws1.Range("B3:N" & lr1).SpecialCells(xlCellTypeVisible).Copy
        ws2.Range("B6").PasteSpecial Paste:=xlPasteValuesAndNumberFormats
        ws1.Range("A6:A" & lr1).AutoFilter
        ws2.Activate: ws2.Cells(1, 1).Activate
End Sub

1 个答案:

答案 0 :(得分:1)

问题是,要调整表的大小,当你知道它的名字时会更容易。

我在代码中添加了3行:

  1. 获取粘贴数据使用的总范围
  2. 为该总范围创建表格
  3. 调整表格的大小(这里没有真正有用的表格)

    Public Sub refresh()
    
    Dim ws1 As Worksheet, ws2 As Worksheet, lr1 As Long, lRow As Long, ResultsRange As String
        Set ws1 = ThisWorkbook.Worksheets("Scénarios de menace")
        Set ws2 = ThisWorkbook.Worksheets("Analyse de risque")
        Application.Calculation = xlCalculationAutomatic
        ws2.Range("B6:N" & ws2.Cells(ws2.Rows.Count, 2).End(xlUp).Row).ClearContents
        lr1 = ws1.Cells(ws1.Rows.Count, 2).End(xlUp).Row
    
        ws1.Range("A1:A" & lr1).AutoFilter Field:=1, Criteria1:="x"
        ws1.Range("B3:N" & lr1).SpecialCells(xlCellTypeVisible).Copy
        ws2.Range("B6").PasteSpecial Paste:=xlPasteValuesAndNumberFormats
        ws1.Range("A6:A" & lr1).AutoFilter
        ws2.Activate
        ws2.Cells(1, 1).Activate
    
        ResultsRange = "$B$6:$N$" & ws2.Range("B"& ws2.Rows.Count).End(xlUp).Row
        ws2.ListObjects.Add(xlSrcRange, Range(ResultsRange), , xlYes).Name = "Results_Table"
        ws2.ListObjects("Results_Table").Resize Range(ResultsRange)
    
    End Sub