英文:
How to format data as a table of variable size in VBA Excel?
问题
Sub FormatTable(workingSheet, N)
workingSheet.ListObjects.Add(xlSrcRange, Range("$A$1:$I$" & N), , xlYes).Name = "Vari Table"
End Sub
英文:
I have loaded data into Excel and want to format the data in a table with a function where I pass the sheet and the number of rows.
Currently I have
Sub FormatTable(workingSheet, N)
workingSheet.ListObjects.Add(xlSrcRange, Range("$A$1:$I$90"), , xlYes).Name = "Vari Table"
End Sub
The size of the table is hardcoded to 90. How do I make it N, the number I pass into the function. Escaping the 90 and replacing it with N does not work.
答案1
得分: 2
Sub FormatTable(workingSheet, N)
workingSheet.ListObjects.Add(xlSrcRange, Range("$A$1:$I$" & N), , xlYes).Name = "Vari Table"
End Sub
英文:
Sub FormatTable(workingSheet, N)
workingSheet.ListObjects.Add(xlSrcRange, Range("$A$1:$I$" & N), , xlYes).Name = "Vari Table"
End Sub
答案2
得分: 0
我会像这样改进您的过程:
Public Function insertTable(ws As Worksheet, numberOfRows As Long, nameOfTable As String) As ListObject
Dim rg As Range
Set rg = ws.Range("$A$1:$I$" & numberOfRows)
Dim lo As ListObject
Set lo = ws.ListObjects.Add(xlSrcRange, rg, , xlYes)
lo.Name = nameOfTable
Set insertTable = lo
End Function
对于您的问题的基本解决方案:您必须使用字符串连接添加数字。
重要提示:
始终使用对工作表本身的明确引用来引用范围。否则,会引用活动工作表,这不一定是您传递给函数的工作表。
在这种情况下,您当前的代码将引发错误。
该函数返回创建的 ListObject
- 以防您需要进行进一步操作。
英文:
I would enhance your procedure like this:
Public Function insertTable(ws As Worksheet, numberOfRows As Long, nameOfTable As String) As ListObject
Dim rg As Range
Set rg = ws.Range("$A$1:$I$" & numberOfRows)
Dim lo As ListObject
Set lo = ws.ListObjects.Add(xlSrcRange, rg, , xlYes)
lo.Name = nameOfTable
Set insertTable = lo
End Function
Basic solution to your question: you have to add the number with a string concatination.
IMPORTANT:
Always use explicit referencing for a range by referring to worksheet itself. Otherwise the active sheet will be referenced which does not need to be the one you are passing to the function.
In this case your current code will throw an error.
This function returns the created ListObject
- just in case you need it for further actions.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论