Using VLOOKUP in Formula - excel

I am getting a compile error on this line but everything seems right to me. I need to put a vlookup inside an if statement which is making this tricky. Can someone catch the error?
Dim k as Integer, numS as Integer
Range(Cells(k, 13), Cells(k, 13)).Formula = _
"=IF(" & Range(Cells(k, 14), Cells(k, 14)).Value & "=" & VLOOKUP(""Weeks from Event " & numS-1 & " to Event " & numS & """, R11C5:R10000C8, 4) & "," & (numS) & ", """")"

I think the error is the RC notation, try R[11]C[5]:R[10000]C[8], but to use VlookUp in VBA I like to use Application.WorksheetFunction...
Sub test()
Dim k As Long
Dim numS As Long
Dim LookUpValue As String
LookUpValue = "Weeks from Event " & numS - 1 & " to Event " & numS
Debug.Print (LookUpValue)
If (Cells(k, 14).Value = WorksheetFunction.VLookup(LookUpValue, Range(Cells(11, 5), Cells(1000, 8)), 4)) Then
Cells(k, 13).Value = numS
Else
Cells(k, 13).Value = ""
End If
End Sub
Let me know if this helps. You can pull up the immediate windows (Ctrl+G) in the VBA editor to see what the value of LookUpValue will be.

Related

Inserting Formula into cells VBA

I am trying to "print" formulas into an excel sheet with VBA.
The code works without the "=" sign in front of the COUNTIF, but when I Insert it I get a Run-Time error 1004.
Can someone help me?
Here is the code that gets the error
Sub Looksie()
Dim Tru As Range
Dim i As Integer
i = 2
For Each Tru In Range("A2:A300")
Sheets("Resultat").Select
Cells(i, 2).Formula = "=COUNTIF(Input!" & Cells(19, i + 1).Address & ":" & Cells(5000, i + 1).Address & ";" & """" & "A" & """" & ")"
i = i + 1
Next Tru
End Sub
Thank you
Could you use next code?
I'm edited only ":" to ",".
Sub Looksie()
Dim Tru As Range
Dim i As Integer
i = 2
For Each Tru In Range("A2:A300")
Sheets("Resultat").Select
Cells(i, 2).Formula = "=COUNTIF(Input!" & Cells(19, i + 1).Address & ":" & Cells(5000, i + 1).Address & ",""A"")"
i = i + 1
Next Tru
End Sub

How to use a variable used as a column tracker in a formula

In a code using a loop, I use a variable as a column tracker. When some conditions are met, I want to insert a formula in a specific cell, using this variable as the column of one of the cell mentioned in the formula.
I created a very similar code, but the variable "m" was a row tracker instead of a column tracker and I was successfully using the following line:
If Cells(8, n).Value = "F" Then Cells(n, 4).Formula = "=AM4-sum(D10:D" & m & ")"
I want to use this m as a column and not as a row, here is a unsuccessful attempt:
If Cells(8, n).Value = "F" Then Cells(11, n).Formula = "=AM4-SUM(Range(Cells(11, 7), Cells(11, " & m & ")))"
Can someone help me about the synthax of the 2d line in order to make it work?
Thanks in advance!
Using Address for Excel Formula
The 1st sub serves as a quick solution to the problem. It can be successfully run if values are assigned to m and n. You can run the 2nd and 3rd subs as they are.
Option Explicit
' A Quick Solution
Sub Quick()
Dim m As Long, n As Long
If Cells(8, n).Value = "F" Then
Cells(11, n).Formula = "=AM4-SUM(" _
& Range(Cells(11, 7), Cells(11, m)).Address(0, 0) _
& ")"
End If
End Sub
' The Versions
Sub Results()
Const EF1 As String = "=AM4-SUM("
Const EF3 As String = ")"
Dim m As Long, n As Long, EF2 As String
n = 1
m = 10 ' At least 10 (Note the different results for 10).
'If Cells(8, n).Value = "F" Then Cells(n, 4).Formula = _
"=AM4-SUM(D10:D" & m & ")"
' Old String Version (You can replace "D" with 4.)
If Cells(8, n).Value = "F" Then
EF2 = "D10:D" & m
Cells(n, "D").Formula = EF1 & EF2 & EF3
End If
Debug.Print "D10:D" & m
' Old Range Version (You can replace "D" with 4.)
If Cells(8, n).Value = "F" Then
EF2 = Range(Cells(10, "D"), Cells(m, "D")).Address(0, 0)
Cells(n, "D").Formula = EF1 & EF2 & EF3
End If
Debug.Print Range(Cells(10, "D"), Cells(m, "D")).Address(0, 0)
'If Cells(8, n).Value = "F" Then Cells(11, n).Formula = _
"=AM4-SUM(Range(Cells(11, 7), Cells(11, " & m & ")))"
m = 7 ' At least 7.
' New Range Version (You can replace "G" with 7.)
If Cells(8, n).Value = "F" Then
EF2 = Range(Cells(11, "G"), Cells(11, m)).Address(0, 0)
Cells(11, n).Formula = EF1 & EF2 & EF3
End If
Debug.Print Range(Cells(11, "G"), Cells(11, m)).Address(0, 0)
End Sub
' A Possible Scenario (Old Range Version)
Sub monitorOldRange()
Const sumFR As Long = 10 ' Sum First Row Number
Const sumLRStart As Long = 11 ' Sum Starting Last Row Number
Const sumCol As Long = 4 ' Sum Column Number
Const srcFC As Long = 1 ' Source First Column Number
Const srcLC As Long = 5 ' Source Last Column Number
Const srcRow As Variant = 8 ' Source Criteria Row Number
Const Criteria As String = "F" ' Source Criteria String
Const tgtCol As Long = 4 ' Target Column Number
Dim scc As Long ' Source Column Counter
Dim sumLR As Long ' Sum Last Row Counter
Dim EF As String ' Excel Formula
Debug.Print String(50, "-") & vbCr & "Old Range Version:"
sumLR = sumLRStart
For scc = srcFC To srcLC
' EF = "=AM64-SUM(D10:D" _
' & fcc _
' & ")"
EF = "=AM64-SUM(" _
& Range(Cells(sumFR, sumCol), Cells(sumLR, sumCol)).Address(0, 0) _
& ")"
Debug.Print Cells(srcRow, scc).Address, Cells(scc, tgtCol).Address, EF
' If Cells(srcRow, scc).Value = Criteria Then
' Cells(scc, tgtCol).Formula = EF
' End If
sumLR = sumLR + 1
Next scc
End Sub

.FormulaR1C1 = Application.WorksheetFunction.CountIfs Arguments not working

I'm trying to use a countifs statement by looking in the first 2 columns and comparing them to another table in the same Wokbook. The reference RrC1, RC1 or anything else does not work. I only get "0" as a result. If i type in constants it works. I'm sure that my arguments 2, 4, 6 are the problem. I just can' figure out why!
Sub DataBase()
'Set my tables
Dim Answers As ListObject
Dim Table As ListObject
Set Answers = Worksheets("quantitativ").ListObjects("DataQuant")
Set Table = Worksheets("Database").ListObjects("Tabelle7")
'Set my Ranges for filters (Organizational level, Location, Function...)
Set OrgRange = Answers.ListColumns(1).Range
Set LocRange = Answers.ListColumns(2).Range
'Set Ranges for Answers to Questions (Scale)
Set Q1 = Answers.ListColumns(5).Range
Dim r As Long 'Row variables for For-Loop
For r = 5 To Table.DataBodyRange.Rows.Count + 4
'Q1
Cells(r, 6).FormulaR1C1 = _
Application.WorksheetFunction.CountIfs(Q1, RrC5, OrgRange, RrC1, LocRange, RrC2)
Next r
End Sub
Cells(r, 6).FormulaR1C1 = _
Application.WorksheetFunction.CountIfs(Q1, RrC5, OrgRange, RrC1, LocRange, RrC2)
This is quite a mess. You're attempting to load a formula with the result of a worksheet function.
If you want to load the formula to the cell then I'd do this:
Cells(r, 6).Formula = "=CountIfs(" & Q1.Address & ", " & _
Cells(r, 5).Address & ", " & OrgRange.Address & ", " & _
Cells(r, 1).Address & ", " & LocRange.Address & ", " & _
Cells(r, 2).Address & ")"
Or even:
Cells(r, 6).Formula = .Formula = "=CountIfs(" & _
Q1.Address & ", E" & r & ", " & _
OrgRange.Address & ", A" & r & ", " & _
LocRange.Address & ", B" & r & ")"
However, if you want the formula evaluated and just the result dumped in the cell..
Cells(r, 6).Value = Application.WorksheetFunction.CountIfs(Q1, _
Cells(R, 5), OrgRange, Cells(R, 1), LocRange, Cells(R, 2))
Keep in mind though with all of these options, Cells(.. are not fully qualified.
Changing all to .Cells(.. would make this much better, wrapping the lot
in a
With WorkSheet("DESTINATION_SHEET")
...
...
End With
is highly advisable.

automatically updating vba concatenate column when changed

I'm concatenating 4 different formula based columns into one using VBA (to be able to change formatting while still concatenating). The concatenating VBA code works, but when the 4 individual columns update and pull the new information, the concatenated column doesn't change.
My concatenated code is this and it lies in column D or 4:
Sub joint1()
ActiveSheet.Range("a2", ActiveSheet.Range("a2").End(xlDown)).Select
Row = 2
Col = 4
For Each Cell In Selection
AE = Cells(Row, Col + 15)
Name = Cells(Row, Col + 9)
SC = Cells(Row, Col + 16)
PM = Cells(Row, Col + 10)
Cells(Row, Col) = Name & Chr(10) & "(" & AE & " - " & SC & ")" & Chr(10) & PM & " - PM"
With Cells(Row, Col)
.ClearFormats
.Characters(1, Len(Name)).Font.Bold = True
End With
Row = Row + 1
Next
End Sub
If you know how to add a feature to help my problem, I would be very appreciative!
Try this:
Option Explicit
Sub joint1()
Dim iRow As Long
Dim iCol As Long
Dim rng As Range
Dim rngSelect As Range
Dim Name As String
Set rngSelect = ActiveSheet.Range("a2", ActiveSheet.Range("a2").End(xlDown))
iRow = 2
iCol = 4
For Each rng In rngSelect
Name = Cells(iRow, iCol + 9)
Cells(iRow, Col) = "=M" & iRow & Chr(10) & " & ""("" & S" & iRow & " & "" - "" & T" & iRow & " & "")"" &" & Chr(10) & "N" & iRow & " & ""-PM"""
With Cells(iRow, iCol)
.ClearFormats
.Characters(1, Len(Name)).Font.Bold = True
End With
iRow = iRow + 1
Next
End Sub
This code creates a formula in each cell, rather than just copying the values.
The job could probably be done just as well with an excel formula. The formatting doesn't work with my version of excel (2007).

Runtime error '1004': application or object defined error

Runtime error '1004': application or object defined error
Hey I cant find out why my code isn't working. I know it's somewhere in the right hand side of the formula. I've highlighted the error for you.
Private Sub CommandButton1_Click() 'accept button
Blank:
machine = TextBox1.Value
rates = TextBox2.Value
If machine = "" Then 'if blank
MsgBox ("Please type in a machine name.")
GoTo DONE
ElseIf rates = "" Then 'if rates is blank
MsgBox ("Please type in a rate for machine.")
GoTo DONE
End If
For i = 1 To 50 'search database
If LCase(Worksheets("database").Cells.Range("B2").Offset(0, i)) = LCase(machine) Then 'if name is in database
MsgBox (machine & " is already in database. Choose another name.")
GoTo DONE
ElseIf IsEmpty(Worksheets("database").Cells.Range("B2").Offset(0, i)) Then 'if it's not
Range("B:B").Offset(0, i).Select
Selection.Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
Worksheets("database").Cells.Range("B2").Offset(0, i) = machine
Worksheets("database").Cells.Range("B2").Offset(0, i).HorizontalAlignment = xlLeft
Worksheets("database").Cells.Range("B2").Offset(-1, i) = rates
For j = 1 To 50
If LCase(Range("A1").Offset(j, 0)) = "total hours" Then
ActiveSheet.Range("B1").Offset(j, i).Formula = "=sum(" & Range(Cells(3, i + 2), Cells(j, i + 2)).Address(False, False) & ")"
ActiveSheet.Range("B1").Offset(1 + j, i).Formula = "=product(sum(" & ActiveSheet.Range(Cells(3, i + 2), Cells(j, i + 2)).Address(False, False) & "," & ActiveSheet.Range(Cells(1, 2 + i)) & ")"
GoTo Cancel
End If
Next j
GoTo Cancel
End If
Next i
Cancel:
DONE:
End Sub
the line that i separate from the others is the one in question.
Thanks!
Hard to know without a description of what you are trying to do. But perhaps:
"=product(sum(" & ActiveSheet.Range(Cells(3, I + 2), Cells(J, I + 2)).Address(False, False) & "," & ActiveSheet.Cells(1, 2 + I).Address & "))"
You need to analyze each part of the line by itself to see what is causing the error. Then put them together after verifying the parts.
Dim HoursRangeAddress As String
Dim RateRangeAddress As String
HoursRangeAddress = ActiveSheet.Range(Cells(3, i + 2), Cells(j, i + 2)).Address(False, False)
RateRangeAddress = ActiveSheet.Cells(1, i + 2).Address
Debug.Print HoursRangeAddress
Debug.Print RateRangeAddress
ActiveSheet.Range("B1").Offset(1 + j, i).Formula = _
"=product(sum(" & HoursRangeAddress & ")," & RateRangeAddress & ")"
You were missing a parenthesis ) after your sum. But also this caused an error: ActiveSheet.Range(Cells(1, 2 + i)) Try this instead: ActiveSheet.Cells(1, 2 + i).Address
Using R1C1 Notation: You should really learn R1C1 notation. Once you are familiar with it, your code is much easier to write and read. You can replace all of the lines of code above with this one line:
ActiveSheet.Range("B1").Offset(1 + j, i).FormulaR1C1 = "=R1C*R[-1]C"
I understand now that you are trying to multiply the rate in row one by the total hours one row above this formula.
It's so much better to use R1C1 notation in a situation like this. You can avoid entirely the need to create string addresses for the formulas. Your formula becomes very simple and easy to read.

Resources