简体   繁体   中英

How to determine the last column(last column with value) using VBA in excel?

I have a question wonder if anyone can help me out.

I'm doing a project that requires to get a summary of tests result. My flow is as follow,

First, I would need to open my collected test results, then creating a pivot table, after setting accordingly to what i need to view, i will copy the table into another spreadsheet. Over at this spreadsheet, it will change some of the names to the required names and finally, it will be copied to the summary sheet. Then i will need to tabulate the summary in % also.

I'm facing with an issue here which is, for my collected test results, when i put it into the pivot table, i cant determine the number of columns that will appear. For example

In on example, we can have 在此处输入图片说明

In another case, we can have

在此处输入图片说明

If u notice the second image has more columns used. Therefore, I was wondering if there is any way that you guys can share with me to determine the last available column with details to be copied.

And can i get the number of the last column so that i can get the summary as well since i need to put it in the form of %.

At the moment, i'm using "Range(A1:Z1000000)" which is quite impossible for me to do anything as i cant really find the % manually.

btw, i need it in VBA code.

Will appreciate for all the opinions and options provided! Thank you in advance!

This should do the trick:

Sub test()

  Dim maxColumn As Long

  'Create the table here
  maxColumn = getMaxUsedColumnNumber("PivotTableSheet")
  'do what you need with the number

End Sub

Function getMaxUsedColumnNumber(sheetName As String) As Long
  With Sheets(sheetName)
    getMaxUsedColumnNumber = .Cells.Find(What:="*", after:=.Range("A1"), LookIn:=xlFormulas, _
            SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Column
  End With
End Function

You can use .SpecialCells() as follows:

ActiveSheet.UsedRange.SpecialCells(xlLastCell).Column

Alternatively, take a look at the ColumnRange property of the PivotTable object. It has a Count property which will return the number of columns in the Pivot Table which could also help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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