How to manage sumproduct with VBA? - excel

I wrote the following code: I'm trying to use sumproduct function with vba but it doesn't work. I've tried with evaluate function but I got the same bad result.
Dim row As Long
Dim rows As Range
Dim us As Integer
Dim rng As Range
Dim rngl As Range
Dim rngo As Range
Dim rngp As Range
With Sheets("Report")
LastRow = .Range("C" & .rows.Count).End(xlUp).row
End With
Set rng = ThisWorkbook.Sheets("REPORT").Range("g3:g" & LastRow)
Set rngl = ThisWorkbook.Sheets("REPORT").Range("F3:f" & LastRow)
Set rngo = ThisWorkbook.Sheets("REPORT").Range("c3:c" & LastRow)
For us = 3 To 33
Range("e" & us).Value = Application.Evaluate("=SUMPRODUCT((sheets(luglio).Range(c & us))<rng)*(sheets(luglio).Range(c & us)=rngl)")
Next us

As Rory mentions in the comments, this isn't working because VBA is passing the entire string inside the quotations marks to Excel. You need to concatenate the strings to get the desired output as you would see in the Excel formula.
Try replacing the line:
Range("e" & us).Value = Application.Evaluate("=SUMPRODUCT((sheets(luglio).Range(c & us))<rng)*(sheets(luglio).Range(c & us)=rngl)")
With:
Range("e" & us).Value = "=SUMPRODUCT((luglio!C" & us & "<REPORT!G3:G" & LastRow & ")*(luglio!C" & us & "=REPORT!F3:F" & LastRow & "))"

Related

Inserting formula using For Next Loop

I am attempting to concatenate a column's worth of fields (~900 at the moment) from two other fields in the same sheet.
I am trying to create a macro to enter the formula into Column C. I can't keep the quotation marks straight.
Sub Concatenate()
Dim i As Long
Dim LastRow As Long
Dim Con As String
Dim WS As Worksheet
Set WS = Sheets("Vlookups")
'Set upper range of Loop
LastRow = Range("C" & Rows.Count).End(xlUp).Row
Application.ScreenUpdating = False
'Set to Active Worksheet
Worksheets("Vlookups").Activate
'Explicitly reference the Sheet when calling for any Range or Cell
With WS
For i = 2 To LastRow
Con = "=CONCATENATE(" & .Cells(i, 15).Select & "," & "-" & "," & .Cells(i, 16).Select & ")"
.Cells(i, 3).Select
ActiveCell.Formula = Con
Next i
End With
Application.ScreenUpdating = False
End Sub
There is no need to Select or Activate.
There is no need to loop.
It looks like you are finding the last row based on column C, but then writing the formula into column C, which seems suspect. Perhaps find the last row based on column O, or column P?
There's no need to use the CONCATENATE formula.
With WS
' find last row based on column O, or maybe P
LastRow = .Range("O" & .Rows.Count).End(xlUp).Row
.Range("C2:C" & LastRow).Formula = "=O2&""-""&P2"
End With
If you actually want hard-coded strings instead of cell references in your formula, then:
With WS
' find last row based on column O, or maybe P
LastRow = .Range("O" & .Rows.Count).End(xlUp).Row
For i = 2 to LastRow
Range("C" & i).Formula = "=""" & Range("O" & i).Value & "-" & Range("P" & i).Value & """"
Next
End With

COUNTIFS formula to refer to a dynamic range in another sheet from the active sheet

I am trying to incorporate this COUNTIFS formula into a worksheet via VBA but cannot seem to get it to work and with my rather limited VBA skills I've hit a bit of a brick wall.
This is the formula I want to incorporate but I want the range to be dynamic rather than fixed:
=IF(COUNTIFS('Scheme Information'!$B$5:$B$20000,COMPILED!$A2,'Scheme Information'!$A$5:$A$20000,COMPILED!H$1)>0,"Yes","")
The VBA code I have written always errors at the .Range stage.
Sub COUNTIFS_Formula()
Dim SourceLastRow As Long
Dim OutputLastRow As Long
Dim sourceSheet As Worksheet
Dim outputSheet As Worksheet
'Name sheets for reference
Set sourceSheet = Worksheets("Scheme Information") ' SOURCE
Set outputSheet = Worksheets("COMPILED") ' OUTPUT
'Determine last row of Scheme Information sheet
With sourceSheet
SourceLastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
End With
'Add in formula
With outputSheet
OutputLastRow = .Cells(.Rows.Count, "B").End(xlUp).Row
.Range("H2:H" & OutputLastRow).Formula = "=IF(COUNTIFS('" & sourceSheet.Name & "!$B$2:$B$" & SourceLastRow & "," _
& outputSheet.Name & "$A2," & sourceSheet.Name & "'!$B$2:$B$" & SourceLastRow & "," & outputSheet.Name & "!H$1)>0" & "," & ""YES"" & "," & "")"
End With
End Sub
It is much easier to solve a problem if you break it down into smaller parts.
.Range("H2:H" & OutputLastRow).Formula = "=IF(COUNTIFS('" & sourceSheet.Name & "!$B$2:$B$" & SourceLastRow & "," _
& outputSheet.Name & "$A2," & sourceSheet.Name & "'!$B$2:$B$" & SourceLastRow & "," & outputSheet.Name & "!H$1)>0" & "," & ""YES"" & "," & "")"
At the very least you should assign the formula to a string variable before you assign it to the Range.Formula. This makes it easy to print the result out to the Immediate Window for inspection.
Sub COUNTIFS_Formula()
Dim Source As Range
Dim SourceFormula As String
With wsSchemeInformation
Set Source = .Range("A2", .Cells(.Rows.Count, "A").End(xlUp)).Offset(0, 1)
SourceFormula = FormulaAddress(Source)
End With
Dim OutputFormula As String, OutputA2Formula As String, OutputH2Formula As String
Dim Output As Range
With wsCompiled
Set Output = .Range("A2", .Cells(.Rows.Count, "A").End(xlUp)).Offset(0, 1)
OutputFormula = FormulaAddress(Output)
OutputA2Formula = FormulaAddress(.Range("A2"))
OutputH2Formula = FormulaAddress(.Range("H2"))
End With
Dim FormulaRange As Range
Set FormulaRange = Output.EntireRow.Columns("H")
Dim FormulaParts As Variant
FormulaParts = Array("=IF(COUNTIFS(", SourceFormula, ",", OutputA2Formula, ",", SourceFormula, ",", OutputH2Formula, ")>0", ",", """YES""", ")")
Dim Formula As String
Formula = Join(FormulaParts, "")
FormulaRange.Formula = Formula
End Sub
Function FormulaAddress(Target As Range)
FormulaAddress = "'" & Target.Parent.Name & "'!" & Target.Address
End Function
Function wsCompiled() As Worksheet ' OUTPUT
Set wsCompiled = ThisWorkbook.Worksheets("COMPILED")
End Function
Function wsSchemeInformation() As Worksheet ' SOURCE
Set wsSchemeInformation = ThisWorkbook.Worksheets("Scheme Information")
End Function

How Do I Automate Multiple Text Filter Contains Sequences and Add The Text Value To The Column To The Right?

I've been trying to implement excel VBA's at work. I have to manually categorise each keyword into categories and my current process is a simple text filter contains then manually add to all cells (GIF to demonstrate at the bottom of the post).
The community has helped me get this far with my VBA code - I'm trying to loop through a range C2:C3 (freehold and leasehold) and then return the value freehold or lease hold in column B next to the relevant keyword.
I'm completely stuck on why this isn't working and I would love a hand.
Here is the excel spreadsheet I'm using to test my macro on
Sub LoopRange()
Dim lastrow, i As Variant
lastrow = Range("A" & Rows.Count).End(xlUp).Row
Dim rCell As Range
Dim rRng As Range
Set rRng = Sheet1.Range("C2:C3")
For Each rCol In rRng.Columns
For Each rCell In rCol.Rows
Debug.Print rCell.Address, rCell.Value
Next rCell
Next rCol
For i = 2 To lastrow
If Range("A" & i).Value Like "*rCell.Value*" Or Range("A" & i).Value Like "*rCell.Value" Or Range("A" & i).Value Like "rCell.Value*" Then
Range("B" & i).Value = "rCell.Value"
End If
Next i
End Sub
There is usually another 20-40 terms just like freehold and leasehold - that is why I need to use a loop through sequence.
P.S. Thank you to those who already replied - you guys have been immensely helpful already and I can't wait to improve my skills and start giving back to this community
Current process of manually adding the keyword categorisation.
Thanks again I really appreciate it guys!
use the below code.
Sub test()
Dim lastrow, i As Long
lastrow = Range("A" & Rows.Count).End(xlUp).Row
For i = 2 To lastrow
If Range("A" & i).Value Like "*freehold*" Or Range("A" & i).Value Like "*freehold" Or Range("A" & i).Value Like "freehold*" Then
Range("B" & i).Value = "yes"
End If
Next i
End Sub
Output:
EDIT 1
As requested, try this with below.
Sub LoopRange()
Dim lastrow As Long, i As Long, lastfilterrow As Long
lastrow = Range("A" & Rows.Count).End(xlUp).Row
lastfilterrow = Range("C" & Rows.Count).End(xlUp).Row
For j = 2 To lastfilterrow
For i = 2 To lastrow
If Range("A" & i).Value Like "*" & Range("C" & j).Value & "*" Then
Range("B" & i).Value = Range("C" & j).Value
End If
Next i
Next j
End Sub

Averaging different length ranges in excel with VBA

I'm trying to write a short macro that includes a line that averages a range of cells. In each worksheet that I want to run the macro in the range of cells is a different length.
After running the macro the cell E1 contains "=AVERAGE(Rng)"
Dim homeSheet As Worksheet
Set homeSheet = ActiveSheet
Dim lastRow As Long
Dim Rng As Range
lastRow = Range("A" & Rows.Count).End(xlUp).Row
Set Rng = Range("B2:B" & lastRow)
Range("E1").Formula = "=Average(Rng)"
Range("E2").Formula = "=STDEV(Rng)"
Range("E3").Select
ActiveWindow.SmallScroll Down:=-2
End Sub
I've also tried
Range("E1").Formula = "=Average(Range("B2:B" & lastRow))"
without trying to use Set Rng = Range("B2:B" & lastRow)
You need to use Rng.Address in your formulas. Try to change your code into this:
Sub Avg()
Dim homeSheet As Worksheet
Set homeSheet = ActiveSheet
Dim lastRow As Long
Dim Rng As Range
lastRow = Range("A" & Rows.Count).End(xlUp).Row
Set Rng = Range("B2:B" & lastRow)
Range("E1").Formula = "=Average(" & Rng.Address & ")"
Range("E2").Formula = "=STDEV(" & Rng.Address & ")"
Range("E3").Select
End Sub
If you were to use the second method you have tried, you would need to change that line of code to:
Range("E1").Formula = "=Average(" & Range("B2:B" & lastRow).Address & ")"

vba to add quotes around cell content using CHR(34) throws "sub not defined" error

I am tiring to write a macro so that every cell in column B gets quote marks around entire string in the cell
I get the error Sub or Function not defined and the CHAR(34) is highlighted
Thanks
Edit: This works now
Sub AddQuotesToCells()
Dim rng As Range, cell As Range
Dim LastRow As Long
With Sheets("sheet1")
LastRow = .Range("A" & .Rows.Count).End(xlUp).Row
Set rng = .Range("B2:B" & LastRow)
For Each cell In rng
cell.Value = Chr(34) & cell & Chr(34)
Next
End With
End Sub
It is not CHAR() it is Chr(). Also, did you forget the . before the range at line Set rng = range...?
And for the formula question:
Change
rng.Formula = "=" & CHAR(34) & "B2" & CHAR(34) & ""
By
rng.Formula = "=""""""" & Chr(34) & "&" & "B2" & "&" & Chr(34) & """"""""

Resources