Insert SUMIF formula in vba without defined range - vba

I have a database sheet (Sheet1) where the datas submitted automatically with userform. everytime a data has been submitted, it will appear on the last row of database. Then I have a column in another sheet (Sheet2) that should show SUMIF formula when the data has been submitted on the Sheet1.
The formula is =SUM.IF(Sheet1!E..:N..,"TRUE",Sheet1!$E$5:$N$5), the problem is The range or row in the formula is not static which means my VBA code has to give the exact row range where a data submitted on the lastrow of Sheet1.
I'm trying to use the formula as a string, But I don't know how to define a dynamic range in my code. The bref code below;
Dim LastRow, LastRow2 As Long
LastRow = Sheet1.Range("B2").Value + 6 (I already put counta formula in the column B2)
LastRow2 = Sheet2.Range("B1").Value + 4 (same here)
Sheet2.Range("E" & LastRow2).Formula = "=SUM.IF(Sheet1!E56:N56,""VRAI"",Sheet1!$E$5:$N$5)"
(the code where i wanna put my formula, and the problem there is on E56:N56 because it must be not static)
I tried with -
Sheet2.Range("E" & LastRow2).Formula = "=SUM.IF(Sheet1!E"&LastRow&":N"&LastRow&",""VRAI"",Sheet1!$E$5:$N$5)"
But it doesn't work.

Related

A code which copies data from a range in one tab to another, however every time the code is run it copies the data the row below. Excel VBA question

My data range needs to be copied from one tab to another. The key to this is it needs to paste the information in the data range into a new row, even if the information is the same. So each time it is run a new row will be populated. Another key here is the row data range consists of criteria, depending on the value of criteria the code will decide which tab to copy into.
I was able to create the code to copy but without if statement and it copies into the same row each time
if Cell E3 = "Revenue" then copy into Revenue worksheet, if not then copy into Cost worksheet.
Each time code is run, the data will be copied into the last unoccupied row available in that worksheet
If I understood You right, this should work:
Sub copy2sheet()
Dim cond As String
Dim lastRow As Integer
With Sheets(ActiveSheet.Name)
'taking name of the sheet from "E3"
cond = .Range("E3").Value
'checking last filled row in sheet we gonna copy data
lastRow = Sheets(cond).Cells(Rows.Count, 1).End(xlUp).row
'copy data starting from "A1" to every cell is close to - CurrentRegion
'a paste it into first empty cell in column "A"
'.Range("A1").CurrentRegion.Copy Sheets(cond).Range("A" & lastRow + 1)
.Range("E3:H3").Copy Sheets(cond).Range("A" & lastRow + 1)
End With
End Sub

Excel VBA: Formula Syntax to refer to Worksheet Index Number (Relative Instead of Name)

I am working on a macro that will filter a database (updated daily) and compute specific formulas. Each time the macro is ran, a new sheet (uniquely named) will be created with the filtered information, and the calculations will be performed on an additional sheet.
I am having trouble creating a macro with the correct syntax. Each time the macro is run, the filtered data I need to reference is located on worksheet #3 (uniquely named). I'm new to VBA and don't understand the syntax I need to reference the worksheet(index) as the worksheet in an R1C1 formula. Right now, my code looks like this:
Dim LR As Long
LR = Worksheets(3).Cells(Rows.Count, 1).End(x1Up).Row
Range("G6").Select
ActiveCell.FormulaR1C1 = _
"=COUNTIF(='Worksheets(3)'!R6C5:R" & LR &"C5,R[-1]C"
The code is counting if a column of Years (of a variable length) is equal to R[-1]C, which is a cell that contains a certain year, and will display the count in cell G6.
Is it possible to use a worksheet(index) reference in this context? How else could I accomplish the task of referencing a worksheet without name? Would I need to reference a "name" variable?
You had an extra = sign in there and you seem to be missing a closing bracket but .Address external:=true produces a nice range reference.
Dim LR As Long, str as string
with Worksheets(3)
LR = .Cells(Rows.Count, 1).End(xlUp).Row
str = .range(.cells(6, 5), .cells(lr, 5)).address(external:=true, ReferenceStyle:=xlR1C1)
end with
Range("G6").FormulaR1C1 = _
"=COUNTIF(" & str & ", R[-1]C)"

VBA Subroutine to fill formula down column

I have a current Sub that organizes data certain way for me and even enters a formula within the first row of the worksheet, but I am running into the issue of wanting it to be able to adjust how far down to fill the formula based on an adjacent column's empty/not empty status. For example, each time I run a report, I will get an unpredictable amount of returned records that will fill out rows in column A, however, since I want to extract strings from those returned records into different Columns, I have to enter formulas for each iteration within the next three columns (B, C, and D). Is there a way to insert a line that will evaluate the number of rows in Column A that are not blank, and then fill out the formulas in Columns B, C, and D to that final row? (I know that tables will do this automatically once information is entered in the first row, but for logistical reasons, I cannot use tables).
My current code that fills out the formula in Column B, Row 2 is:
Range("B2").Select
ActiveCell.FormulaR1C1 = "=MID(RC[-1],FIND(""By:"",RC[-1])+3,22)"
Thanks!
The formula that you actually need is
=IF(A2="","",MID(A2,FIND("By:",A2)+3,22))
instead of
=MID(A2,FIND("By:",A2)+3,22) '"=MID(RC[-1],FIND(""By:"",RC[-1])+3,22)"
This checks if there is anything in cell A and then act "accordingly"
Also Excel allows you to enter formula in a range in one go. So if you want the formula to go into cells say, A1:A10, then you can use this
Range("A1:A10").Formula = "=IF(A2="","",MID(A2,FIND("By:",A2)+3,22))"
Now how do we determine that 10? i.e the Last row. Simple
Sub Sample()
Dim ws As Worksheet
Dim lRow As Long
'~~> Change the name of the sheet as applicable
Set ws = ThisWorkbook.Sheets("Sheet1")
With ws
'~~> Find Last Row in Col A
lRow = .Range("A" & .Rows.Count).End(xlUp).Row
.Range("B2:B" & lRow).Formula = "=IF(A2="""","""",MID(A2,FIND(""By:"",A2)+3,22))"
End With
End Sub
More About How To Find Last Row
You can use this to populate columns B:D based on Column A
Range("B2:D" & Range("A" & Rows.Count).End(xlUp).Row).Formula = _
"=MID($A2,FIND(""By:"",$A2)+3,22)"

Excel VBA - Insert Row & Insert Column Macros

I have a "Task Tracker" workbook that uses columns A:J to display and calculate task information (A:E are for user-entered data, F:J contain formulas that use the information in C:E and perform calculations. F:J are hidden cells in the user view.) The remainder of the columns display a heat map of where the tasks fall on a timeline, and whether or not they are running on time, are behind, or are complete.
There are two buttons for users to use: one to insert a new row, and one to insert a new column. The InsertRow() macro inserts a row into the list, then copies the formulas down from the above row. The InsertColumn() macro locates the last used column in the worksheet and copies everything over from the column to the left of it.
Originally, I had a macro for InsertRow using Range that copied from Column F (where the formulas start) to Column XFD. However, once I created the InsertColumn macro I realized that I cannot do InsertRow like that because InsertColumn needs to locate the last data-containing column in the worksheet and add a new one to the right...and if InsertRow gets run first, InsertColumn won't work because the value for lastColumn comes back as the index of column XFD.
What I am looking for help with:
I need to locate the lastColumn value in my InsertRow macro, then use that value as part of the Range when the program executes the Copy/Paste portion of the code. I think that the problem I'm having has to do with the fact that the code I'm using to find the last column returns the index, and the Range function needs the name of the column.
Here is what I have for both macros:
Sub InsertTaskRow()
' InsertTaskRow Macro
'
' This macro inserts a new row below whatever role the user currently has selected, then
' copies the formulas and formatting from above down to the new row
Dim lastColumn As Long
Dim currrentRow As Long
Dim newRow As Long
lastColumn = ActiveSheet.Range("A1").SpecialCells(xlCellTypeLastCell).Column
currentRow = ActiveCell.Row
newRow = currentRow + 1
ActiveCell.Offset(1).EntireRow.Insert Shift:=xlDown
Range("F" & currentRow & ":" & lastColumn & currentRow).Copy Destination:=Range("F" & newRow & ":" & currentRow & newRow)
End Sub
Sub InsertColumn()
' InsertColumn Macro
'
' This macro copies the formulas and formatting from the last data-containing column
' in the worksheet, and pastes it into the next column to the right.
Dim lastColumn As Long
lastColumn = ActiveSheet.Range("A1").SpecialCells(xlCellTypeLastCell).Column
MsgBox lastColumn
Columns(lastColumn).Copy Destination:=Columns(lastColumn + 1)
End Sub
You can try changing your lastColumn occurances to the following:
lastColumn = ActiveSheet.Range("A1").End(xlToRight).Column
This will stretch your range to all used cells. I tried using the clCellTypeLastCell, but it was pulling further than necessary for no apparent reason; even after deleting the entire columns it claimed were applicable. Just an FYI, there is no issue with using indexes or column names when utilizing Range() - even interchangibly, they are both fully qualified.

VBA Absolute Formula range changing when running a copy + Paste macro

I am running a copy paste macro but when I run it, it keeps changing the range of my formula to the last of row.
For example, my original VLOOKUP formula looks from $D$2:$G$5000, but when I run my macro it will change it to $D$2:$G$1254 where 1254 is the last row where data resides.
Here is the copy + paste function:
Sub START1()
Dim shCurrentWeek As Worksheet
Dim shPriorWeek As Worksheet
Dim lr As Long
Set shCurrentWeek = ActiveWorkbook.Sheets("Current Week")
Set shPriorWeek = ActiveWorkbook.Sheets("Prior Week")
lr = shCurrentWeek.Range("A" & Rows.Count).End(xlUp).Row
'Copies Current Week into Prior Week and deletes Rows in Prior week
shCurrentWeek.Range("A4:X" & lr).Copy
shPriorWeek.Range("A2").PasteSpecial xlPasteValues
shPriorWeek.Range("A" & lr - 2 & ":A10000").EntireRow.Delete
End Sub
any ideas?
You can use the INDIRECT() function so the formula will always reference the rows you wish. Here's a simple example (please see this link for way more detailed info):
=SUM(INDIRECT("A1:A6"))
For a start you are using pastevalues so you will not be getting any formulas on your second page but your error lies with the last row of your code
shPriorWeek.Range("A" & lr - 2 & ":A10000").EntireRow.Delete
Because your formula overlaps this range that you are deleting excel automatically adjusts the vlookup formula.
I would suggest deleting your data before pasting the values.
*edit after reading the comments if the formulas are already on the page then this solution will not work and I would use clearcontents instead as per tim's suggestion.