简体   繁体   English

Excel:使用 VBA 时表格不调整大小

[英]Excel: Table not resizing when using VBA

I am relatively new to coding in general, but here goes:一般来说,我对编码比较陌生,但这里有:

I have a huge list of membershipdata which I am trying to organize.我有一个庞大的会员数据列表,我正在尝试组织这些数据。 This is going to be done weekly as the data is variable, so I am trying to automate the work a bit.由于数据是可变的,这将每周进行一次,因此我正在尝试使工作自动化一点。

I have written (with help) a code that copies an entire row of data if a specific cell contains a specific text, and pastes it in another sheet under an existing table.我已经(在帮助下)编写了一个代码,如果特定单元格包含特定文本,则复制整行数据,并将其粘贴到现有表格下的另一个工作表中。

However, when doing this using a macro, the table doesnt resize accordingly, like it would do when using ctrl+c and ctrl+v.但是,当使用宏执行此操作时,表格不会相应地调整大小,就像使用 ctrl+c 和 ctrl+v 时所做的那样。 Ie when there is more data this week then last, the table isnt large enough, and so the sorting options in the table wont sort all the data.即当这周有更多数据时,表不够大,因此表中的排序选项不会对所有数据进行排序。

I have been able to resize the table using this code:我已经能够使用以下代码调整表格的大小:

Sub sortOK()

Dim sht As Worksheet
Dim LastRow As Long
Dim LastColumn As Long
Dim StartCell As Range

Set sht = Worksheets("OK")
Set StartCell = Range("A1")

  Worksheets("OK").UsedRange

  LastRow = StartCell.SpecialCells(xlCellTypeLastCell).Row
  LastColumn = StartCell.SpecialCells(xlCellTypeLastCell).Column

  sht.Range(StartCell, sht.Cells(LastRow, LastColumn)).Select

  sht.ListObjects("OK").Resize Range(StartCell, sht.Cells(LastRow, LastColumn))

End Sub

This works fine, however it only works when I am viewing this specific sheet, I cant operate it from another sheet.这工作正常,但是它仅在我查看此特定工作表时才有效,我无法从另一张工作表操作它。 How can I do so?我怎么能这样做?

I would also like to do the same operation in one go on four other lists, each in its own spreadsheet.我还想一次性对其他四个列表执行相同的操作,每个列表都在自己的电子表格中。

I have been stuck on this problem alost an entire day, and my head is about to explode!在这个问题上纠结了一整天,头都快炸了!

Thank you in advance.先感谢您。

Try like this:像这样尝试:

Set StartCell = sht.Range("A1")

It should work.它应该工作。 This way, you are referencing the worksheet to the range as well.这样,您也将工作表引用到该范围。 If you do not do it, it takes the ActiveSheet.Range("A1") .如果你不这样做,它需要ActiveSheet.Range("A1")

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

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