Using SUMIF until last row in vba - vba

I'm trying to incorporate a SUMIF formula into my macro. The code in excel looks like this: =SUMIF('WSO Interest' H2:H46, '20140618 Loans' D10, 'WSO Interest' S2:S46)
I set my dim as i and lastrow as integer
I already set that so that I can find the last row of the column and continue my loop until the last row.
I also used
Sheets("20140618 Loans").Select
Range("A10").Select
Selection.End(xlDown).Select
lastrow = ActiveCell.Row
to find the last row filled with text.
This is what
I have so far:
Range("W10").select
For i = 10 to lastrow
SUMIF formula would go here
Next i
So basically what I'm trying to do is use the SUMIF formula in my macro to start at W10 and keep calculating the SUMIF formula until it reaches the last row. Thanks for the help and feel free to ask any questions.

You can use the Formula property of a Range object to set the formula.
Range("W" & i).Formula = "=SUMIF('WSO Interest'!H2:H" & lastrow & _
", '20140618 Loans'!D10, 'WSO Interest'!S2:S" & lastrow & ")"
The & operator is used to concatenate strings together.

Dim r As Range
Set r = Range("W10", Range("W10").End(xlDown)) --Change it per requirement .....
For Each cell In r
Debug.Print cell.Address --Your Code goes here I guess
Next

Related

r1c1 formula not working

I am trying to rank values using column J and tie breaker in column K with the result populating in column N. Column J & K are values.
Somehow it only generates one value wherever my cell is pointed at, which means if I run the vba codes at cell C19, it will just populate value 1 in C19, not from N6 where I want the results to be.
Here are my codes,
Sub test()
Dim LR1 As Long
LR1 = Range("J" & Rows.Count).End(xlUp).Row
With Range("N6:N" & LR1)
ActiveCell.FormulaR1C1 = "=1+SUMPRODUCT(--(R6C10:R33C10<RC[-4]))+SUMPRODUCT(--(R6C11:R33C11<RC[-3]),--(R6C10:R33C10=RC[-4]))"
End With
End Sub
I am not sure what went wrong. I tried to do it manually using the excel formula and its working fine but not my vba codes.
ActiveCell is your issue.
Change
ActiveCell.FormulaR1C1 = "=1+SUMPRODUCT(--(R6C10:R33C10<RC[-4]))+SUMPRODUCT(--(R6C11:R33C11<RC[-3]),--(R6C10:R33C10=RC[-4]))"
To .FormulaR1C1 = "=1+SUMPRODUCT(--(R6C10:R33C10<RC[-4]))+SUMPRODUCT(--(R6C11:R33C11<RC[-3]),--(R6C10:R33C10=RC[-4]))"
Remove that and it should do what you want.
You will want to fully qualify your Range references that way they aren't depending on the ActiveSheet. This will provide you with consistent behavior and results.

MS Excel VBA - Loop Through Rows and Columns (Skip if Null)

Hello stackoverflow community,
I must confess I primarily code within MS Access and have very limited experience of MS Excel VBA.
My current objective is this, I have an expense report being sent to me with deductions in another countries currency, this report has many columns with different account names that may be populated or may be null.
I currently have a Macro that will open an input box and ask for the HostCurrency/USD Exchange rate, my next step will be to start at on the first record (Row 14; Column A-K contains personal info regarding the deduction) then skip to the first deduction account (deduction accounts start at column L and span to column DG) checking if each cell is null, if it is then keep moving right, if it contains a value then I want to multiply that value by my FX rate variable that was entered in the input box, and update the cell with the converion. Once the last column (DG) has been executed I want to move to the next row (row 15) and start the process again all the way until the "LastRow" in my "Used Range".
I greatly appreciate any feedback, explanations, or links that may point me towards my goal. Thank you in advance for taking the time to read though this!
First off, you really should attempt to write the code yourself and post what you have so someone can try to point you in the right direction. If your range is going to be static this is a very easy problem. You can try something along the lines of:
Sub calcRate(rate As Double, lastrow As Integer)
Dim rng As Range
Set rng = Range("L14" & ":DG" & lastrow)
Dim c As Variant
For Each c In rng
If c.Value <> "" Then
c.Value = c.Value * rate
End If
Next
End Sub
This code will step through each cell in the given range and apply the code without the need for multiple loops. Now you can call the calcRate sub from your form where you input the rate and lastrow .
This will do it without looping.
Sub fooooo()
Dim rng As Range
Dim mlt As Double
Dim lstRow As Long
mlt = InputBox("Rate")
With ActiveSheet
lstRow = .Cells(.Rows.Count, 1).End(xlUp).Row
Set rng = .Range(.Cells(14, 12), Cells(lstRow, 111))
rng.Value = .Evaluate("IF(" & rng.Address & " <>""""," & rng.Address & "*" & mlt & ","""")")
End With
End Sub
If your sheet is static you can replace ActiveSheet with WorkSheets("YourSheetName"). Change "YourSheetName" to the name of the sheet.

Autofill to new last row from previously last row after data is added?

I have a database that is growing quite large. Every day I add about 100 rows of information.
I have about 20 columns that autofill with calculations, etc. A few of those columns pull from a VERY large file using Vlookups. That takes forever because it's pulling the entire column everyday because my current autofill macro starts in row 2.
Is there any way to write the macro so that it autofills from the previous "last row" so it's only autofilling 100 or so new rows instead of several thousand?
I have tried the following with no luck:
Range("BZ2").AutoFill Destination:=Range("BZ2:BZ" & LastRow) is an example of one of my VBA codes for an autofill I use. LastRow is the last row after the new data is pasted in. I would like it to ideally start at the OldLastRow which would be the last row before I paste in the new data. I tried Range("BZ" & OldLastRow).AutoFill Destination:=Range("BZ" & OldLastRow & ":BZ" & LastRow) without luck.
Try this.
Dim LastRow As Long
With ActiveSheet
'This will get you the OldLastRow. Add +1 to the end to get the first empty row if you need it.
'The "A" in .Rows.Count, "A" should be replaced with a column that will always have data in every row.
LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
.Range("BZ2").AutoFill Destination:=Range("BZ2:BZ" & LastRow)
'This will pause the macro until Calculations are complete.
Do While Application.CalculationState <> xlDone
DoEvents
Loop
End With
Ideally you would be doing the autofill from the point that you pasted your data in, so you wouldnt want to have "BZ2" anywhere in there if you just want to autofill new data.
you could try this one as well.
Dim LastRow As Long
With ActiveSheet
LastRow = .Cells(.Rows.Count, "BZ").End(xlUp).Row
.Range("BZ2").AutoFill Destination:=Range("BZ" & LastRow & ":BZ" & Cells(Rows.Count, "BY").End(xlUp).Row)
Do While Application.CalculationState <> xlDone
DoEvents
Loop
End With
This is assuming you only have one column of calculations. if not change the "BZ" & LastRow & ":BZ" to "BZ" & LastRow & ":CA" or whatever your last calculated column is.

Excel VBA Copy and Paste Loop within Loop

I’ve been working on this VBA code for a while and since I’m a complete noob I feel like I haven’t gotten anywhere. I’ve been researching a ton, but can’t seem to combine answers to help with my scenario.
Essentially what I’m trying to do is grab data, line by line, from one worksheet and extrapolate it to another worksheet. I believe this will involve loops and I’m so new with VBA I don’t know how to do it.
Here’s the logic I’m attempting:
For each row on worksheet 1, I would like to perform 3 different copy and paste activities to worksheet 2 and then it will loop down to the next row on sheet1 and do the 3 activities and so on. This will continue downwards until column A is blank in sheet1. Sheet1 data starts at A3 and sheets2 paste area starts at A2.
The first activity is to copy cells F3,D3,A3, and H3 (in that order so F3 will be A2, D3 will be B2 etc) from sheet 1 to sheet 2 to A2,B2,C2, etc. A destination functions can’t be used because I need just the values and no other formats—one of the many issues I’ve ran in to.
The next activity is to copy cells F3,D3,A3 and I3 from sheet 1 to sheet2 pasted below the previous copy and paste—again no formats just values. Also to note, some of these may be blank (except A column) but I still need that row there with at least column A data—this goes to say with all these activities.
The third activity is to copy and paste sheet1’s F3,D3, and A3 a certain number of times referencing K3’s number—and each copy and paste will be in the next available blank cell. So if the number in K3 it will look like it created 3 rows in sheet2—totaling 5 rows on sheet2 since activity1 and 2 each create their own row.
After these three activities are completed for row 3 on sheet 1, it will then move to row 4 and do the previous three activities and paste to sheet2. And again it will be pasting no formats and in the next blank row on sheet 2. Also again, this loop will stop once the cell in Column A is blank.
Below is my incomplete code. I don’t even think it will help one bit and it would probably be better not to even look at it. I’ve just started to get frustrated since I can’t even do a simple copy and paste, yet alone loops within loops. I also haven’t even started on my third activity. I greatly appreciate it!
Sub copyTest3()
Dim proj As Range, release As Range, pm As Range, lead As Range, coord As Range
Dim leadCopy As Range, coordCopy As Range
Dim i As Range
Set proj = Range("A3", Range("A3").End(xlDown))
Set release = Range("D3", Range("D3").End(xlDown))
Set pm = Range("F3", Range("F3").End(xlDown))
Set lead = Range("H3", Range("H3").End(xlDown))
Set coord = Range("I3", Range("I3").End(xlDown))
Set leadCopy = Union(pm, release, proj, lead)
Set coordCopy = Union(pm, release, proj, coord)
For i = 1 To Range(ActiveSheet.Range("A3"), ActiveSheet.Range("A3").End(xlDown))
leadCopy.Copy
Sheets("Sheet2").Activate
Range("A2").Select
ActiveSheet.PasteSpecial xlPasteValues
Application.CutCopyMode = False
Sheets("Sheet1").Activate
coordCopy.Copy
Sheets("Sheet2").Activate
Range("A2").Select
ActiveSheet.PasteSpecial xlPasteValues
Next i
End Sub
There are many ways to do this, and some are more efficient than others. My solution may not be the most efficient, but hopefully it will be easy for you to understand so that you can learn.
It's very difficult to understand what you're attempting to do in activity three, so I wasn't able to provide a solution to that step. Use my code as a template for step three and if you run into issues, feel free to leave a comment.
Notice that I don't use .Activate, .Select, or .Copy in this code. .Activate and .Select are huge efficiency killers, and they make it easier for your code to "break," so avoid using them when possible. .Copy isn't necessary when working with values or formulas and will also slow your code down.
Untested
Sub testLoopPaste()
Dim i As Long
Dim ii As Long
Dim i3 as Long
Dim LastRow As Long
Dim wb As Workbook
Dim sht1 As Worksheet
Dim sht2 As Worksheet
Set wb = ThisWorkbook
Set sht1 = wb.Sheets("Sheet1")
Set sht2 = wb.Sheets("Sheet2")
'Find the last row (in column A) with data.
LastRow = sht1.Range("A:A").Find("*", searchdirection:=xlPrevious).Row
ii = 2
'This is the beginning of the loop
For i = 3 To LastRow
'First activity
sht2.Range("A" & ii) = sht1.Range("F" & i).Value
sht2.Range("B" & ii) = sht1.Range("D" & i).Value
sht2.Range("C" & ii) = sht1.Range("A" & i).Value
sht2.Range("D" & ii) = sht1.Range("H" & i).Value
ii = ii + 1
'Second activity
sht2.Range("A" & ii) = sht1.Range("F" & i).Value
sht2.Range("B" & ii) = sht1.Range("D" & i).Value
sht2.Range("C" & ii) = sht1.Range("A" & i).Value
sht2.Range("D" & ii) = sht1.Range("I" & i).Value
ii = ii + 1
'Third activity
For i3 = 1 To sht1.Range("K" & I)
sht2.Range("A" & ii) = sht1.Range("F" & i).Value
sht2.Range("B" & ii) = sht1.Range("D" & i).Value
sht2.Range("C" & ii) = sht1.Range("A" & i).Value
ii = ii + 1
Next i3
Next i
End Sub
The way I usually approach copying data between sheets in Excel is to create source range and destination range objects, each range referring to just one row. When I want to move on to the next row, I use Offset to return a range offset to the next row.
Since the ranges only refer to one row, you can index them with an integer to get the cells in the row. E.g. if cursor refers to columns A through D in row 3, cursor(3) will give you the cell C3.
Dim src_cursor As Range
Dim dest_cursor As Range
Set src_cursor = ActiveSheet.Range("A3:I3")
Set dest_cursor = Sheets("Sheet2").Range("A2:D2")
'' Loop until column A is empty in source data
Do Until IsEmpty(src_cursor(1))
dest_cursor(1) = src_cursor(6) '' copy F -> A
dest_cursor(2) = src_cursor(4) '' copy D -> B
'' and so on
'' move cursors to next row
Set src_cursor = src_cursor.Offset(1, 0)
Set dest_cursor = dest_cursor.Offset(1, 0)
Loop
Also, this might be getting a little off topic, but it's a better practice to use an Enum to name the column numbers instead of hardcoding them like I did here.

#NAME error when setting cell formula through VBA.

I am writing a macro that requires me to get the average of the values in a column with an unknown number of rows. I use this to get the number of the last row:
Dim lastRow As Long
lastRow = ActiveSheet.UsedRange.SpecialCells(xlCellTypeLastCell).Row
That works. What doesn't work is when I try to use it here:
Range("B2").Select
ActiveCell.FormulaR1C1 = "=AVERAGE('table1'!AM2:AM" & lastRow & ")"
Doing that, I get a result of #NAME?. How can I fix this?
Change ActiveCell.FormulaR1C1 to ActiveCell.Formula since you're using basic A1 notation and not R1C1.