I've got a relatively small table (2-5 rows / 7-9 columns) that I'm trying to loop through and calculate values using .formula. I'm having some issues figuring out how I refer to the absolute values of the column or row of the cell that I'm on. Here's what I've hard-coded so far:
For i = 1 To Range("GapTable").Rows.Count
For i2 = 2 To Range("GapTable").Columns.Count
Range("GapTable").Cells(i, i2).Formula = "=IFERROR(ROUND(AVERAGEIFS(prof_gap, series, $A21, grade, B$20),2), ""N/A"")"
Next i2
Next i
I'm trying to figure out how to change $A21 to lock the column in as an absolute, and B$20 to lock the row in, with the formula copying to the adjacent cells correctly (the same as if you took the cursor and filled in the values). The code works now, but obviously the values are all the same. Any suggestions how I address this issue, or a better way of doing this?
As written in my comment, you can paste over the range, where the dynamic references are to the upper left cell, e.g.,
with Range("GapTable")
.range(.cells(1,2),.cells(.Rows.Count,.Columns.Count)).Formula = "=IFERROR(ROUND(AVERAGEIFS(prof_gap, series, $A21, grade, B$20),2), ""N/A"")"
end with
If you have to loop, you can use counters, e.g.:
dim colnum as long, rownum as long
For i = 1 To Range("GapTable").Rows.Count
For i2 = 2 To Range("GapTable").Columns.Count
Range("GapTable").Cells(i, i2).Formula = "=IFERROR(ROUND(AVERAGEIFS(prof_gap, series, $A" & rownum & ", grade, " & cells(20,colnum).address & "),2), ""N/A"")"
colnum = colnum + 1
Next i2
rownum = rownum + 1
Next i
Note that you have to convert the column number to an address, which is why the cell() reference includes the 20.
I did not include the error handling for resetting rownum/colnum to reset back to 20/2, respectively. Just throwing out the concept if for some reason you can't just paste over the range.
Edit1: forgot the . in front of cells(1,2) in the withstatement for pasting over a range.
Related
Heylo, I am trying to write an excel function that takes a user-selected range and performs different calculations based on the column the cell being populated lines up with. The screenshot below shows the setup of the columns.
I want to set AA5 to be "=myFunction($AA1:$AD4)", and then I want click-and-drag to use the autofill feature to populate AB5, AC5, and AD5 with the same "=myFunction($AA1:$AD4)" but this myFunction will do different things based on which cell is being populated during the autofill.
I know how to do this in a subroutine where the user would select the first open cell AA5, and is prompted for the range to use for calculations. I would do something along the lines of:
Sub CalcCells()
Dim myRange As Range
Set myRange = Application.InputBox("Select the cells you want to use...", Type:=8)
Dim numColumn As Long
For numColumn = 0 To myRange.Columns.Count - 1
Select Case numColumn
Case Is = 0
ActiveCell.Offset(0, numColumn).Formula = "=SUM(" + myRange.Columns(1) + ")"
Case Is = 1
ActiveCell.Offset(0, numColumn).Formula = "=SUMPRODUCT(" + myRange.Columns(1) + "," + myRange.Columns(2) + ")"
Case Is = 2
ActiveCell.Offset(0, numColumn).Formula = "=SUMPRODUCT(" + myRange.Columns(1) + "," + myRange.Columns(3) + ")/SUM(" + myRange.Columns(1) + ")"
Case Is = 3
ActievCell.Offset(0, numColumn).Formula = "=SUMSQ(" + myRange.Columns(4) + ")"
End Select
Next numColumn
End Sub
So basically I want to do exactly this, but I want it to be a function that when I click and drag and autofill AB5:AD5 it knows which column the cell lines up with and performs a calculation based on that, and uses it as an argument/parameter almost. It will not always be 4 rows either, so it needs to be capable of accommodating varying row counts, but the .Columns should work with that as long as the user selects only the same datatype.
Is this possible and how can I do it? Thank you for any help in advance. I've done a lot of searching and I don't know if I'm not searching the right way, but i cannot find anything that really helps.
What about something like this? Basically, you get the column of the cell you enter the formula into with Application.Caller.Column. Then inputRange.Column gives you the leftmost column of your input range. Based on the difference of the two, you know which worksheet function you want to use. If the difference is 0, your formula is entered in the 1st column, so you use Sum. If the difference is 1, you use Sumproduct, and so on.
Function SummarizeCells(inputRange As Range) As Double
Dim col As Long
col = Application.Caller.Column - inputRange.Column
Select Case col
Case 0
SummarizeCells = WorksheetFunction.Sum(inputRange.Columns(1))
Case 1
SummarizeCells = WorksheetFunction.SumProduct(inputRange.Columns(1), inputRange.Columns(2))
Case 2
SummarizeCells = WorksheetFunction.SumProduct(inputRange.Columns(1), inputRange.Columns(3)) / WorksheetFunction.Sum(inputRange.Columns(1))
Case 3
SummarizeCells = WorksheetFunction.SumSq(inputRange.Columns(4))
End Select
End Function
A sample view here:
I want to put a Sum formula in a row of a table, in columns C to H, but the code I’ve come up with somehow doesn’t work. The situation is as follows:
the number of the 1st row of the table varies (the 1st column is
always B)
the number of the 1st row in the formula varies, but is always the 3rd row of the table
the number of the row that should contain the formula varies, but in the macro I calculate that number relative to the 1st row of the table
the number of the last row in the formula varies, but is always 1 less than the number of the row that should contain the formula
To be more specific and hopefully more clear, let’s say that:
the number of the first row of the table = startnum
then the number of the 1st row in the formula = startnum+3
the number of the row that should contain the formula = startnum+x
then the number of the last row in the formula = startnum+x-1
Trying to find out what my code could be, I recorded a macro. Based on that I have tested the following code:
With Worksheets("A&N")
.Range("C16:H16").Formula = "=SUM(C7:C15)"
End With
This works fine, but as I’ve described, the numbers 16, 7 and 15 are actually variable.
I’ve tried to translate this code to my situation, and made this code:
Set rngOpmaak = Range(rngTabel.Cells(startnum + x, 2), rngTabel.Cells(startnum + x, 7))
rngOpmaak.Formula = "=SUM(“C” & startnum + 3 & “:C” & startnum + x -1)"
When I run the macro I get the message that the second line can’t be compiled. I’ve seen solutions on this site that to me look exactly like my code, so I don’t understand what’s wrong with mine.
I’ve also tried:
rngOpmaak.FormulaR1C1 = "=SUM(R" & startnum + 3 & "C:R" & startnum + x -1 & "C)"
But with startnum=2 (1st row of the table) the formula becomes =SUM(C$3:C$5) to =SUM(H$3:H$5) (without the quotations) instead of =SUM(C4:C6) to =SUM(H4:H6).
Can anyone help me with what the line of code should be? All suggestions are much appreciated.
You'll need to adjust this to your situation, as I didn't use the same variables you did (preferring more expressive ones):
Sub test()
Dim output As Range, dataStart As Integer, dataEnd As Integer, rowsOfData As Integer, nCols As Integer
' Row 1: Table headers
' Row 2: 1st row of data
' Row 3: more data
' Row 4: more data
' Row 5: last row of data
' Row 6: Summary row (location of formula)
dataStart = 2
dataEnd = 5
rowsOfData = 1 + dataEnd - dataStart
nCols = 4
Set output = Range(Cells(dataEnd + 1, 1), Cells(dataEnd + 1, nCols))
output.FormulaR1C1 = "=SUM(R[-" & rowsOfData & "]C:R[-1]C)"
End Sub
The generated formula uses relative references, as it was given offsets ([]) from the current cell, rather than absolute R/C values, e.g.
R2C:R5C -> A$2:A$5 no matter where in column A the formula is entered
R[-4]C:R[-1] -> A2:A5 if the formula is entered in A6.
In Microsoft Excel I want to create a table to be something like in picture below.
I already try using vlookup and index but I can't make it work like I want.
Please help me
Try to use VBA:
Sub TransformTbl()
Dim i As Long, j As Long, cnt As Long
With ActiveSheet
.Range("G1:I1") = Array("Date", "Event", "Place")
cnt = 1
For j = 2 To 4 'column
For i = 2 To 5 'row
If Len(.Cells(i, j)) <> 0 Then
cnt = cnt + 1
.Cells(cnt, 7) = .Cells(1, j) 'Date
.Cells(cnt, 8) = .Cells(i, j) 'Event
.Cells(cnt, 9) = .Cells(i, 1) 'Place
End If
Next i
Next j
End With
End Sub
I wrote a solution and it works fine with me. The formula is really complex and probably hard to understand. Though I'll try my best to explain it, updating the formula may still be a difficult work. All these three formula are written in Array Formula, press ctrl+shift+enter to complete.
Formula in G6:
=IFERROR(OFFSET($A$5,0,SMALL(
IF($B$6:$D$9<>"",1,99999999)*(COLUMN($B$6:$D$9)-1),ROW(A1))),"")
The outer IFERROR keeps your sheet from any #Err. The OFFSET for calling the right date. The formula inside SMALL generate an array with the rule: If there is an event, the value will be the number of the date for offset, otherwise, it will be 99999999 which giving the OFFSET an error and be blocked by IFERROR. With the data you gave, the array will be
{ 1,99999999, 3;
1, 2,99999999;
1,99999999,99999999;
99999999,99999999, 3 }
Formula in H6:
=IFERROR(OFFSET($A$5,
SMALL(IF($B$6:$D$9<>"",ROW($B$6:$D$9)-5)*
IF(COLUMN($B$6:$D$9)=MATCH(G6,$B$5:$D$5,0)+1,1,99999999),99999999),COUNTIF($G$6:G6,G6)),
MATCH(G6,$B$5:$D$5,0)),"")
The IFERROR and OFFSET works the same as G6. The formula in OFFSET.ROW generate nearly the same array as G6. This time the value is the row of event with the date determined by column G. Other gives 999999999 or more.
Formula in I6:
=IFERROR(OFFSET($A$5,MAX((ROW($B$6:$D$9)-5)*($B$6:$D$9=H6)*
(COLUMN($B$6:$D$9)=MATCH(G6,$B$5:$D$5,0)+1)),0),"")
IFERROR and OFFSET are still the same. And this time only the event which matches the date and the name of itself has a value, other remains 0.
Finally, I apologize for the poor readability. Wish someone can help me out with this :]
Right - this is a tricky one to phrase so I'm going to use a couple of images to help me.
In Columns A and B is a varying list of team names and the number of players each team has.
Column D contains the desired output.
I need a formula, to be inserted into Cell D2 and dragged down as far as the total of Column B, to return the team names - but crucially to allow a number of rows beneath which return blank. The number of blank rows beneath is effectively equal to 1 - the number of players in that team.
I have given it some thought, but can't come up with a suitable formula. Any ideas?
Also suggestions for a better title are welcome.
The following VBA function will do exactly what you want. Let me know if any part of it is not clear to you.
Sub teamRows()
Dim colDRowNumber As Integer
Dim i As Integer
Dim teamName As String
Dim numberOfRows As Integer
Dim HowFar As Integer
' Loop through the teams in column A
HowFar = Application.WorksheetFunction.CountA(Range("A:A"))
' Variable to keep count of rows in column D
colDRowNumber = 2
For i = 2 To HowFar
' Get the team's name and number of rows
teamName = Range("A" & i).Value
numberOfRows = Range("B" & i).Value
' Fill in the team's name in column D
Range("D" & colDRowNumber).Value = teamName
' Increase the row number by the number of empty rows required
colDRowNumber = colDRowNumber + numberOfRows
Next i
End Sub
A complex but short attempt - I wanted to avoid loops.
Example below works on A2 to A20
y = Split(Join(Application.Transpose(Application.Evaluate("=index(substitute(substitute(substitute(REPT(A2:A20 &"","",B2:B20),A2:A20&"","",""X"",1),A2:A20,""""),""X"",A2:a20),0,1)")), ","), ",")
[d2].Resize(UBound(y)) = Application.Transpose(y)
I've got a workbook where I have one worksheet which contains a lot of data.
My goal is to create a macro that inserts a formula in a separate sheet to copy the data from the first sheet. Lets call the first sheet "Numbers1" and the second sheet "TidyNumbers1".
In the sheet "TidyNumbers1" I want to loop through each cell from column A to M and rows 1 to 60. So I've got a macro that so far looks like this:
Sub updateFormulasForNamedRange()
Dim row, col, fieldCount As Integer
colCount = 13
RowCount = 60
For col = 1 To colCount
For row = 1 To RowCount
Dim strColCharacter
If col > 26 Then
strColCharacter = Chr(Int((row - 1) / 26) + 64) & Chr(((row - 1) Mod 26) + 65)
Else
strColCharacter = Chr(row + 64)
End If
Worksheets("TidyNumbers1").Cells(row, col).Formula = "=IF(Numbers1!E" & col & "<>0;Numbers1!" & strColCharacter & row & ";"")"
Next row
Next col
End Sub
But the formula is supposed to looks like this for Column A, row 2:
IF(Numbers1!E2<>0;Numbers1!A2;"")"
And the formula in Column A, row 3 should look like this:
IF(Numbers1!E3<>0;Numbers1!A3;"")"
Formula in Column B, row 2 should look like this:
IF(Numbers1!E2<>0;Numbers1!B2;"")"
In other words, the formula looks to see if the value in Column E, row % is anything but 0 and copies it if conditions are met.
But, I see that I need to translate my integer variable Row with letters, because the formula probably needs "A" instead of 1. Also, I get a 1004 error (Application-defined or object-defined error) if I just try to use:
Worksheets("Numbers1").Cells(row, col).Formula = "=IF(Numbers1!E" & row & "<>0;Numbers1!" & col & row & ";"")"
I clearly see that the integer row should be translated to letters, if that's possible. Or if anyone has any other suggestions that might work. Also, the 1004 error is unclear to me why happens. I can define a string variable and set the exact same value to it, and there's no error. So it's probably the formula bar that whines about it I guess?
Here is a former post of mine containing functions for conversion of column numbers to letters and vice versa:
VBA Finding the next column based on an input value
EDIT: to your 1004 error: Try something like this:
=IF(Numbers1!E" & row & "<>0,Numbers1!A" & row & ","""")"
(use ; instead of ,, and "" for one quotation mark in a basic string, """" for two quotation marks).
Would not it be easier to get the cell address with the Cells.Address function?
For example:
MsgBox Cells(1, 5).Address
Shows "$E$1"
Best Regards