VBA - sum if rows hidden below - excel

I am making a org chart with values attached at each level. I already have a simple hide rows VBA. How can I add on to it so that for example
if the value of Company A (e.g. J11) = values of Companies 1, 2, and 3, which are displayed in H14, J14, and L14
then when row 14 is hidden, then J11= sum(H14, J14, L14)
and when row 14 is visible, then J11 = 0
This is what i have so far just to hide/unhide rows.
Sub sbHideAll()
Rows("10:25").EntireRow.Hidden = True
End Sub
Sub sbShowAll()
Call sbHideAll
Rows("10:25").EntireRow.Hidden = False
End Sub
Sub sbShowGUCL()
Call sbHideAll
Rows("10:11").EntireRow.Hidden = False
End Sub

You can't do it directly but you can get the value of the visible cells.
So take the value of the range like this:
Application.WorksheetFunction.Sum(Union(Range("H13:H100"), Range("J13:J100"), Range("L13:L100")))
then take the value of the visible cells using .Rows.SpecialCells(xlCellTypeVisible) like this:
Application.WorksheetFunction.Sum(Union(Range("H13:H100").Rows.SpecialCells(xlCellTypeVisible), Range("J13:J100").Rows.SpecialCells(xlCellTypeVisible), Range("L13:L100").Rows.SpecialCells(xlCellTypeVisible)))
Then minus one from the other
You can either assign each to a variable or just plop it straight into J11 like so:
Range("J11").Formula = Application.WorksheetFunction.Sum(Union(Range("H13:H100"), Range("J13:J100"), Range("L13:L100"))) - Application.WorksheetFunction.Sum(Union(Range("H13:H100").Rows.SpecialCells(xlCellTypeVisible), Range("J13:J100").Rows.SpecialCells(xlCellTypeVisible), Range("L13:L100").Rows.SpecialCells(xlCellTypeVisible)))

Related

Is there an Excel formula to move a set of cells by a specific amount in each direction?

I tried using the OFFSET function to no avail. Essentially, I have a few cells and I need to move them by a user-specified amount in the x and y direction. How would I do this?
In excel, a function like this one will populate multiple cells
Function populate()
Evaluate "eventFinal(" & Application.Caller.Offset(0, 1).Address(False, False) & ")"
populate = "result here >>"
End Function
Private Sub eventFinal(CellToChange As Range)
Dim numbers(2, 1) As Integer
numbers(0, 0) = 25
numbers(0, 1) = 21
numbers(1, 0) = 3
numbers(2, 0) = 4
numbers(1, 1) = 2
numbers(2, 1) = 6
CellToChange.Resize(3, 2) = numbers
End Sub
I'm afraid VB is the only way unless you 'cheat' a little...
I only illustrate the concept re: 'cheating' with this google sheet.
Google sheets "equivalent" with colour placement: here.
The alternative would be block out a range of cells with functions such as:
=if(and(row(A1) - row(A$1) = row offset value, column(A1)-column(A$1 = column offset value), desired cell to move, "")
The suitability of this depends entirely upon the purpose: if your goal is a visual one where the actual values don't really matter, then google sheets example is one method but the value you place is quite limited (can only use values

How to add all available value or label filters from a pivot table into a listbox? (Excel VBA)

Okay, so I have a pivot table where there is a column of provinces and other columns of sales per years.
I have created macros through vba to apply filtering on the pivot table.
(Recorded macros)
I want to add all available label and value filters into a listbox eg:
Label filters are :
Equals...
Does not equal...
Begins with...
Etc...
I want all of them in a listbox, or combobox, or anything the user can click and expand to select what filter they want.
Any help please?
jamesalainheffer#gmail.com
Okay well I seemed to have figured it out. Most people don't know about the filtering options in excel. And if they do, they probably would go about doing it in VBA by saying something like
`With
ActiveSheet.PivotTables("pvt_Data").PivotFields("Province")`
.PivotItems("Yukon").Visible = false
and so on... By just making the field or item not visible, doesn't neccessarily mean you're applying a filter to anything...
So, here's what I found...
dim prov as string
dim letter as string
dim val2 as string
dim pvtPivotTable as PivotTable
dim pfdValueField as PivotField
dim pfdTRowField as PivotField
set pvtPivotTable = ActiveSheet.PivotTables("pvt_Data")
set pfdValueField = ActiveSheet.PivotTables("Sum of Sales")
set pfdTRowField = pvtPivotTable.PivotFields("Province")
letter = TextBox4.Value
prov = TextBox1.Value
msg = ", Caption Filters, " & listbox1.value
with pvtPivotTable
.AllowMultipleFilters = True
pfdTRowField.PivotFilters.Add2 Type:=Listbox1.Value, Value1:=prove, Value2:=letter
end with
set pfdValueField = nothing
set pfdRowField = nothing
filterlistbox.AddItem(Listbox1.Text & " " & prov & msg
now what this does along with the rest of my projects is it loads every xlFilterType into 3 listboxes, per categpry of Caption filters (text), Value Filters (numerical), and date filter (date)
3 listbox's for 3 categories of filter types, each listbox is loaded with them (filter types [xlBefore, xlCaptionIsEqual]) when you select a filter type, enter a value into a textbox and push a button and it weill then apply that filter onto my pivot table.
The listbox where the filter type gets added I did like this:
.addItem("Equall...")
.list(0, 1) = "15"
What this does is add that "Equall" to the list box, the list statement just inserts 15 into the 2nd column on the 1 st index (index starts at 0, 1 is the 2nd column)
Now, the xlFilterTypes have a value as well as a name for example XlCaptionEqualls is the name and its value is 15, the listbox1.value is this value becuase i set the bound column to number 2, so the listbox pushes out the filterTypes value (number) instead of the text I hard coded, you can then use case statements to get the name from the value and insert them into another listbox.
this is a bit all over the show but I would like to know if nayone has managed to add multiple filters onto their pivot table using vba? and the add2 method?
Kick ass.

Referencing a cell with Offset generates Error 1004 application defined or object defined error

I have to adjust sales volumes so that
1) I do not use up my daily capacity and
2) I do not run out of window by the end of the month
I need two criteria and to run until it either hits my end date or runs out of window at the end of the month.
Dates are in column A.
I have
Sub CashCalib()
Set Window = Sheets("inventory").Range("AX124")
Set Capacity = Sheets("Inventory").Range("BU95")
Set Sales = Sheets("Inventory").Range("BV95")
Set EndDate = Sheets("inputs").Range("A1")
Do Until Sales.Offset(0, -74) = EndDate
Capacity.GoalSeek _
Goal:=0 And Window.Value > 0, _
ChangingCell:=Sales
Loop
End Sub
I get
run time error 1004 application defined or object defined error
on the do until line.
Your Sales.Offset(0, -74) is moving left too far as you do not have 74 columns to go left. If you meant to move up then do Sales.Offset(-74, 0) or change to which value you need to move up. Just remember that there is not a 0 row or column in excel like many other languages.
You were receiving a Error 1004 Object error because you were offsetting one column too many. By offsetting Column BV (the 74th column) -74 columns, you were offsetting to column 0, which doesn't exist.
Modify your Do Until line to look like this:
Do Until Sales.Offset(-94, -73) = EndDate

Adding several elements to a listbox menu in vba

I am trying to create a menu with list boxes in order to be able to select a number of customers from a list in an excel sheet. There are two list boxes, one with all the (default) data and one with the selected customers.
There is no problem adding one customer but when I add a second customer the graphic interface shows nothing, but after some debugging, the SelectedCustomers.RowSource still have the two rows in its data:
?SelectedCustomers.RowSource
$8:$8,$11:$11
This would have me believe there is some error with how I save the data or some limitations to Excel that I am not aware of. This is the code I use to save the data:
Private Sub CommandButton5_Click()
Dim temp As Range
For i = 0 To DefCustomers.ListCount - 1
If DefCustomers.Selected(i) = True Then
If temp Is Nothing Then
Set temp = Range(Rows(i + 4).Address)
Else
Set temp = Application.Union(temp, Range(Rows(i + 4).Address))
End If
End If
Next i
SelectedCustomers.RowSource = temp.Address
End Sub
Has someone experienced this before or know what the problem might be?
Instead of RowSource use AddItem method:
For i = 0 To DefCustomers.ListCount - 1
If DefCustomers.Selected(i) Then
SelectedCustomers.AddItem DefCustomers.Selected(i)
End If
Next i
There are known issues with ListBox.RowSource property in Excel VBA.
[EDIT]
After the discussion...
No matter of number of columns, you can copy rows from source sheet into another sheet, then bind SelectedCustomers listbox to that data

Convert text to number in Excel in VBA [duplicate]

This question already has answers here:
VBA: Convert Text to Number
(11 answers)
Closed 4 years ago.
For some reason Excel is converting my number into text and adding a preceding apostrophe in every cell in column E3 and F3.
I need to convert columns E3:F3 back to numbers and format them to currency. How do I do that?
A1:K2 is the header.
The code below is not working:
Set wb = objApp.Workbooks.Open("aFile.xls", True, False)
wb.Sheets(1).Rows(2).Delete
wb.Sheets(1).Range("E3:F3") = Mid(wb.Sheets(1).Range("E3:F3"), 2,
Len(wb.Sheets(1).Range("E3:F3")) - 2)
wb.Sheets(1).Range("E3:F3").NumberFormat = "$#,##0.00"
If your text is only a number, the answer is simple. Multiply it by 1.
Say cell A1= '00001234 or a formula or macro returns a piece of text, multiply the answer by 1.
"00001234" * 1 = 1234.
I want to extract the value of a Label or a txtBox on a VBA form.
Num = lblText * 1
Another example:
If .txtLevel10 * 1 > 50 Then...etc.
Also works with some other data types "16-Jan-15" *1 = 16/1/15
Works in Excel & VBA but only if there are no other characters in the original text.
Cheers
Assuming you want the same currency formatting you get from the toolbar, this works:
wb.Sheets(1).Range("E3:F3").Formula = wb.Sheets(1).Range("E3:F3").Value
wb.Sheets(1).Range("E3:F3").Style = "Currency"
Just using worksheet.Range() with no properties forces Excel to guess exactly which property you actually mean (this is called the "default property"), and you get inconsistent results.
Try:
Range("E3:F3").Style = "Currency"
Try highlighting that column and doing Data->Text To Columns (Excel 2003; in 2007+ Text to columns is on one of the ribbons). Click 'Delimited', then 'Next', Next again, then select General as the format. This should convert the whole column into a number.
If this works, it is easily automated. Let me know if you need code.
EDIT - you have to do one column at a time.
Len(wb.Sheets(1).Range("E3:F3"))
For me this just (as expected) throws an error. You'll have to process each cell individually to use your approach.
Dim c as Range
Set wb = objApp.Workbooks.Open("aFile.xls", True, False)
With wb.Sheets(1)
.Rows(2).Delete
For each c in .Range("E3:F3").cells
c.Value = Mid(c.value, 2, Len(c.value)-2)
c.NumberFormat = "$#,##0.00"
next c
End With
This, actually, works. The key is to apply format before setting the value:
Set wb = objApp.Workbooks.Open("aFile.xls", True, False)
wb.Sheets(1).Rows(2).Delete
wb.Sheets(1).Range("E3:F3").NumberFormat = "$#,##0.00"
For Row = 3 To 3 'your rows range in case you need iterate through (1 row only in your case)
For Column = 5 To 6 'E3:F3
wb.Sheets(1).Cells(Row, Column) = Mid(wb.Sheets(1).Cells(Row, Column), 2, Len(wb.Sheets(1).Cells(Row, Column)) - 2)
Next Column
Next Row

Resources