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

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.

Related

Filtering Pivot Table column

I tried and looked on this forum and Others but I couldn't find the right working code yet.
I want to filter on a pivot table a column with values equal or higher than 10%.
When I recorded my macro, code was as follow:
Sub Macro9()
Macro9 Macro
ActiveSheet.Range("$A$5:$M$36607").AutoFilter Field:=13, Criteria1:=">=0.1" _
, Operator:=xlAnd
End Sub
This doesn't work but I wanted to launch the macro afterwards.
So I tried other codes, like the following :
Sub FilterPivotTable()
Application.ScreenUpdating = False
ActiveSheet.PivotTables("PivotTable1").ManualUpdate = True
ActiveSheet.PivotTables("PivotTable1").PivotFields("Name of my column").ClearAllFilters
ActiveSheet.PivotTables("PivotTable1").PivotFields("Name of my column").PivotFilters. _
Add Type:=xlCaptionEquals, Value1:=">=0.1"
ActiveSheet.PivotTables("PivotTable1").ManualUpdate = False
Application.ScreenUpdating = True
End Sub
But this didn't work either.
Can anyone please help me?
Thank you very much in advance.
EDIT: Apparently, the fact that my field is a calculated one is important. Still don't have an answer though.
So, I found myself an answer to my question.
Since the columns I wanted to filter were values and calculated fields, I actually needed to filter these columns by right-clicking on a cell inside a row value of my PVT. Then, I had to filter by chosing the right value to sort and add my criteria.
The code when recording a macro is as follow:
ActiveSheet.PivotTables("PivotTable1").ClearAllFilters
ActiveSheet.PivotTables("PivotTable1").PivotFields("Your row name").PivotFilters. _
Add2 Type:=xlValueIsGreaterThanOrEqualTo, DataField:=ActiveSheet. _
PivotTables("PivotTable1").PivotFields("Your value field"), Value1:=0.1
Hope it can help some of you, as I haven't seen an answer to this issue in many forums.
Have a nice day!

duplicate a complex (double) table row in ms word vba

in Microsoft Word 2010, say I have a template with a table, which contains some ready column headers, and the first row. this row is complex - basically it spans two real rows. it also has uneven column widths in the first and the second "real" rows. e.g.
i am trying to populate this table with a dynamic number of rows, that i need to be like the first one. e.g.
the methods that i've seen this far that add rows to a table all make the new row look like the last row (or the first - depending on the way you do it) - but i want the same functionality to be extended to two rows, i.e. so that the new TWO rows would look like the last TWO rows.
the only way i found is to use clipboard. i want to avoid clipboard. maybe anyone can think of another way?
the clipboard code that works:
Sub example()
Set myrows = ActiveDocument.Range( _
ActiveDocument.Tables.Item(1).Rows.Item(1).Range.Start, _
ActiveDocument.Tables.Item(1).Rows.Item(2).Range.End _
)
myrows.Select
' this works
myrows.Copy
myrows.Paste
' this adds two rows that look like the last row in the selection
' this is not what i need
'Selection.InsertRowsBelow
End Sub
thanks
I'm sorry, it's an example of forgetting what you learned like 10 years ago. The particular question I asked seems to be easily answered.
Sub example()
Set myrows = ActiveDocument.Range( _
ActiveDocument.Tables.Item(1).Rows.Item(1).Range.Start, _
ActiveDocument.Tables.Item(1).Rows.Item(2).Range.End _
)
' this works
Set rowsbelow = ActiveDocument.Range(myrows.End, myrows.End)
rowsbelow.FormattedText = myrows.FormattedText
End Sub
if moderators deem it necessary, i may delete the post entirely

updating VBA Custom Functions

I have the following function(which returns the last row number of any selected column)
Function LastrowCC(SelectedRange As Range)
Dim SelectedColumnNum As Long
SelectedColumnNum = SelectedRange.Column
LastrowCC = ActiveSheet.Cells(Rows.count, SelectedColumnNum).End(xlUp).Row
End Function
the problem is that when the last row of the selected column is deleted the function does not update automatically
can we make VBA custom functions update automatically when inputs change?
At risk of repeating the helpful comments and answers already posted, let me point out that there are several issues involved in your question, summed up nicely in the MSDN article "Excel Recalculation."
A more specific question, including the Excel version and the way calculation is handled on your worksheet, may help narrow things down a bit.
Let me sum up some things you may want to check out, all listed in the article above:
There are several ways a recalculation is triggered, including functions. Studying the way this happens may shed some insight. According to the article, "The calculation of worksheets in Excel can be viewed as a three-stage process:
Construction of a dependency tree,
Construction of a calculation chain,
Recalculation of cells."
Volatile functions are an option, but because of resource consumption should be used sparingly and wisely.
You may also explore Range.Dirty and Range.Calculate methods, which starting in Excel 2002 (that's farther back in the past than some of us realize!) allows "forced recalculation," to again quote the article above.
These are a few options and things to consider.
Make it Volatile :
Function LastrowCC(SelectedRange As Range) As Long
Application.Volatile
Dim SelectedColumnNum As Long
SelectedColumnNum = SelectedRange.Column
LastrowCC = ActiveSheet.Cells(Rows.Count, SelectedColumnNum).End(xlUp).Row
End Function
The key to making a function work within Excel's calculation tree and not be volatile is to include everything you need in the arguments to the function. That is, don't reference any ranges that are not included in the arguments to the function.
In your example, you can send it any single cell and it will return the last row of that same column. But you're looking outside of that single cell so Excel doesn't know that the whole column should be in the calculation tree.
In this rewrite, the function only accepts single, whole column arguments. If you send it less than a whole column, it returns an error. If you send it more than one column, it returns an error. But since the whole column is in the argument, any changes in the column trigger a recalc.
Public Function LastRowCc(ByVal SelectedRange As Range)
If SelectedRange.Address = SelectedRange.EntireColumn.Address And SelectedRange.Columns.Count = 1 Then
LastRowCc = SelectedRange.Find("*", SelectedRange.Cells(1), , , , xlPrevious).Row
Else
LastRowCc = CVErr(xlErrValue)
End If
End Function

Using a function to return a value in VBA without using the worksheet

Good afternoon One and All,
I am relatively new to VBA and I am trying to use the Worksheet function, specifically the index function to look up information in the code and bring back a value. I would love to do this without having to assign it to a cell in the worksheet using R1C1. Is there a way to do Vlookups, or Indexex without having to make assignments in the worksheet?
The examples below works as an equation placed within the sheet, but I'd like to get the same answer without having to use the sheet.
The first formula looks up a Batch number
The second formula is finding the name of the first ingredient in the batch, based on the SKU in the worksheet.
ActiveCell.FormulaR1C1 = _
"=VLOOKUP(RC[-1],'U:\Files\Maintenance File.xls'!SKUinfo,16,FALSE)"
ActiveCell.FormulaR1C1 = _
"=INDEX('U:\Files\[Recipe File.xlsx]Fresh 2800'!Fresh2800,2,6)*(INDEX(SchedInfo,MATCH(RC[-3],SKULookup,0),6))"
Any help would be appreciated, and thank you for all your help in advance.
The answer to this Microsoft forum post describes what you want. Use the Application object:
ans = Application.VLookup(arg1, MyRange, arg3, arg4)

Excel VBA PivotCaches won't accept source

I created a sub that automatically creates a pivot table based on a source range. The code works fine when the source data is a small range. However, when I run it on some bigger data (110'000 rows) I get run time error 13 (Type Mismatch).
I don't understand why it does this. I can run the exact same code on another range, and all is well???
Does someone have a suggestion why this would happen?
Set rDataRange = wsData.Range("A1").CurrentRegion
' Create the cache
Set PTCache = ActiveWorkbook.PivotCaches.Create( _
SourceType:=xlDatabase, _
SourceData:=rDataRange)
This question appears to be asking (and answering) a very similar question: Type mismatch error when creating a pivot table in Excel with VBA
Are you absolutely sure your reference to the larger range is valid? Are you positive the larger range is not missing a header, doesn't contain an extra blank row or column, doesn't have any bad data?