遍历列表并将数据更改为表

时间:2018-10-03 17:01:31

标签: excel vba

此处是初学者VBA。作为较大宏的一部分,我将在完成较早的过程(本部分已经完成)之后从另一个工作簿中引入工作表,但是随后我想更改引入表中的数据。因为此工作簿中有数百个选项卡,所以我认为拥有一个选项卡名称列表进行遍历是最简单的选择。我有以下内容,但似乎无法正常工作。我认为我唯一想念的就是激活它选择的任何工作表。 (会有更多的A1:A2,我只是在较小的范围内进行测试):

Sub TabstoTables()

    Dim tablename As Range
    Dim tbl As ListObject
    Dim rng As Range

    Application.ScreenUpdating = False

    For Each tablename In Sheets("Tab Names").Range("A1:A2")

        Set rng = Range(Range("A1"), Range("A1").SpecialCells(xlLastCell))
        Set tbl = ActiveSheet.ListObjects.Add(xlSrcRange, rng, , xlYes)
        tbl.TableStyle = "TableStyleMedium15"

    Next tablename
End Sub

感谢任何帮助!!非常感谢

2 个答案:

答案 0 :(得分:0)

尝试一下:

Sub TabstoTables()
Dim sht As Worksheet
Dim tbl As ListObject
Dim rng As Range

On Error GoTo Err
    Application.ScreenUpdating = False
    For Each sht In ActiveWorkbook.Sheets
        rng = sht.UsedRange
        Set tbl = ActiveSheet.ListObjects.Add(xlSrcRange, rng, , xlYes)
        tbl.TableStyle = "TableStyleMedium15"
    Next sht
    Application.ScreenUpdating = True
    Exit Sub
Err:
    Application.ScreenUpdating = True
    MsgBox "There was an error"
End Sub

您可以遍历工作表本身,而不必具有工作表名称的列表。

此外,请注意“ On Error”和“ Err:”之后的代码。如果您的过程中有错误,这将处理Application.ScreenUpdating = True的重置。按照当前编写代码的方式,如果代码一直沿线某处失败,则ScreenUpdating会停留在False(假)状态,而现在您的状态非常糟糕。

答案 1 :(得分:0)

这是您的代码,但有一些更改:

Sub TabstoTables()

    Dim tablename As Variant
    Dim TargetSheet As Worksheet
    Dim tbl As ListObject
    Dim rng As Range       

    For Each tablename In Sheets("Tab Names").Range("A1:A2")
        Set TargetSheet = Worksheets(CStr(tablename))
        Set rng = Range(TargetSheet.Range("A1"), TargetSheet.Range("A1").SpecialCells(xlLastCell))
        Set tbl = TargetSheet.ListObjects.Add(xlSrcRange, rng, , xlYes)
        tbl.TableStyle = "TableStyleMedium15"     
    Next tablename
End Sub