如何在VBA Excel中将数据格式化为可变大小的表格?

huangapple go评论60阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2023年1月9日 18:19:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/75055823.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定