简体   繁体   English

用于表格格式化的VBA。

[英]VBA for Table Formatting.

I have sheet1, sheet2 , sheet3, sheet4. 我有sheet1,sheet2,sheet3,sheet4。

Of the 4 Sheets, sheet 1 and sheet2 has data in list. 在这4张工作表中,工作表1和工作表2在列表中有数据。 and sheet3 and sheet 4 has Pivot tables for the same. sheet3和sheet4具有相同的数据透视表。

I would like to have a VBA, in such a way that, in my workbook, if it find Sheets with list, then it shoudl Format it to table. 我想要一个VBA,以这种方式,在我的工作簿中,如果找到带有列表的工作表,则应将其格式化为表格。 The table should be only for the cells it has value. 该表应仅适用于它具有值的单元格。

I used record macro, to get the code, but i am struck how i should implement it for all my Sheets. 我使用了记录宏来获取代码,但是我对如何为所有工作表实现它感到惊讶。 the code, from record macro for one sheet: 代码,来自一张纸的记录宏:

sub macro()
  Cells.Select
    ActiveSheet.ListObjects.Add(xlSrcRange, Range("$1:$1048576"), , xlYes).Name = _
        "Table2"
    Cells.Select
    ActiveSheet.ListObjects("Table2").TableStyle = "TableStyleLight9"
End Sub

通常,当我从数据源复制时,它类似于下图

我想要这样的VBA,无需手动操作即可更改上面的图形。

I think you meant something like the code below: 我认为您的意思类似于以下代码:

Option Explicit

Sub macro()

Dim ws As Worksheet
Dim ListObj As ListObject

For Each ws In ThisWorkbook.Worksheets
    With ws
        For Each ListObj In .ListObjects
            ListObj.TableStyle = "TableStyleLight9"
        Next ListObj
    End With
Next ws

End Sub

If your question is that change range to Listobject, look at follow code. 如果您的问题是Listobject的更改范围,请查看以下代码。

Sub macro()
    Dim Ws As Worksheet
    Dim LstObj As ListObject
    Dim rngDB As Range, n As Integer

    For Each Ws In Worksheets
        With Ws
            Set rngDB = .Range("a1").CurrentRegion
            For Each LstObj In Ws.ListObjects
                LstObj.Unlist
            Next
            If WorksheetFunction.CountA(rngDB) > 0 Then
                n = n + 1
                Set LstObj = .ListObjects.Add(xlSrcRange, rngDB, , xlYes)
                With LstObj

                    .Name = "Table" & n
                    .TableStyle = "TableStyleLight9"
                End With
            End If
        End With
    Next Ws

End Sub

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

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