Excel에서 VBA 코드를 실행하여 단추를 클릭 한 후 테이블 (ListObject)을 작성합니다. 헤더 이름에 대한 모음을 사용하여 열이 동적으로 추가됩니다. 테이블을 작성하기 전에 오류를 방지하기 위해 기존 테이블이 삭제됩니다.Excel VBA : 워크 시트에 열을 추가하지 않고 ListObject에 열 추가
ListColums.Add
을 사용할 때 문제는 전체 시트에 열을 추가하고 기존 열을 오른쪽으로 밀어 넣는 것입니다. 따라서 버튼을 클릭 할 때마다 시트에는 더 많은 열이 있습니다. 이것은 매우 깨끗하지 않습니다. 단추는 매우 자주 누르고 Excel 워크 시트의 한계를 넘지 않도록하고 싶습니다.
Function buildTable(wsName As String, tblName As String, clmns As Collection, Optional tableRange As String)
' * If Range is not specified choose "$A$1"
If IsMissing(tableRange) Then
position = "$A$1"
End If
' * Build the table based on the passed parameters
ThisWorkbook.Worksheets(wsName).ListObjects.Add(xlSrcRange, ThisWorkbook.Worksheets(wsName).Range(tableRange), , xlYes).Name = tblName
' * Declare and define tblName as ListObject in Worksheet wsName
Dim tbl As ListObject
Set tbl = ThisWorkbook.Worksheets(wsName).ListObjects(tblName)
' * Declare and define the columns of table tblName
Dim clmn As ListColumns
Set clmn = tbl.ListColumns
' * Replace the first column name with the first item in our column Collection clmns
tbl.HeaderRowRange(1, 1).Value = clmns.Item(1)
' * Now loop through the rest of the passed header name collection clmns. Start with 2, because 1 was already set in the last step
X = 2
For X = 2 To clmns.Count
' * Add Item X to the table (String from the passed collection clmns) as column.
clmn.Add.Name = clmns(X)
Next X
End Function
내가 이런 식으로 전화 할게 : 다음과 같이 내 빌드 기능이 작동
' * Declare and fill my Collection of headers
Dim clHeaders As New Collection
clHeaders.Add "MyFirstColumn"
clHeaders.Add "MySecondColumn"
clHeaders.Add "MyThirdColumn"
' * Call the builTable Function
Call buildTable("Sheet1", "MyTable", clHeaders)
가 이미 ThisWorkbook.Worksheets("Sheet1").Columns("AS").EntireColumn.Delete
을했지만, 이것은 단지 이미 빈 열을 비우고 삭제하지 않습니다 ..
버튼을 클릭 할 때마다 시트 끝에 더 많은 열이 없으면이를 수행 할 수있는 방법이 있습니까?
먼저 시트의 열 수를 늘릴 수 없습니다. 항상 동일하게 유지됩니다. 둘째로, 'EntireColumn.Delete'는 셀의 전체 열을 삭제하지만, 이전처럼 전체 열의 수는 항상 동일하게 유지됩니다. – Rory
감사합니다, 당신은 저에게 올바른 생각을 가져 왔습니다! – 30000MONKEYS