VBA用于覆盖较小的表下拉列表

时间:2016-11-13 03:38:16

标签: vba

以下VBA的功能和效果如下: - 我有几个表,并为每个表使用命名范围。 - 然后,在另一个选项卡上(代码所在的位置)我有两个下拉列表,以便我的Excel报表的用户可以选择他们想要显示数据的表(一次只能一个)。

问题对我来说,如果我从下拉列表中选择一个包含30行的表,看起来都很好 - 表目标单元格A2。但是,如果然后我选择一个只有10行的表,那么10行的新表将覆盖在前30行表上,但10行表下的20行(从30行表中剩余)仍然在那里。< / p>

我的问题是: 我应该如何更改下面的代码,以便从下拉列表中选择10个rwo表时不会出现上一个表中的20行?

如果上述内容没有意义,请告诉我。谢谢v。

我的代码如下:

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim tableName As String
    Dim tableRange As Range
    Dim TypeOfCosts As String
    Application.EnableEvents = False

    If Range("B1").Text = "Fixed Staff Costs" Then
        TypeOfCosts = "_Fixed_Staff"
    ElseIf Range("B1") = "Variable Staff Costs" Then
        TypeOfCosts = "_Variable_Staff"
    ElseIf Range("B1") = "Production Costs" Then
        TypeOfCosts = "_Production"
    ElseIf Range("B1") = "Infrastructure Costs" Then
        TypeOfCosts = "_Infrastructure"
    ElseIf Range("B1") = "Other Costs" Then
        TypeOfCosts = "_Other"
    Else
        TypeOfCosts = ""
    End If

    tableName = Range("A1").Text & TypeOfCosts & "_Costs"

    On Error Resume Next
    Set tableRange = Application.Range(tableName)
    Debug.Print ThisWorkbook.Names.Count
        If Not (tableRange Is Nothing) And Err = 0 Then
        tableRange.Copy Destination:=Range("A3")
    Else
        Err.Clear
    End If
    On Error GoTo 0
    Application.EnableEvents = True
End Sub

2 个答案:

答案 0 :(得分:0)

ClearContents(清除数据):清除从A3到CurrentRegion中最后一个单元格的所有数据,保留任何列标题:

Range("A3",Range("A3").CurrentRegion.SpecialCells(xlCellTypeLastCell)).ClearContents

清除(数据和格式):要清除数据和格式:

Range("A3",Range("A3").CurrentRegion.SpecialCells(xlCellTypeLastCell)).Clear

答案 1 :(得分:0)

这是一种非常直率的方法,但不了解您的设置:

With Range("A3").Resize(1000,10)
    .ClearContents
    .ClearFormats
End with