Vba to vlookup value & copy next cell value to invoice sheet - vba

Formula use for Vlookup
activeWS.cell("A9") =INDEX(Breaking_Data!F5:F,MATCH(A8,Breaking_Data!A5:A,0))
I try to run it in VBA code but it doesn't work, any one know how to modify it for VBA code.
that lookup A8 cell value in ws("Breaking_Data") with Range("A5:A").lastcellvalue if any value match then copy same row cell value form range ("F5:F") & paste it in active sheet cell A9.

Try this:
dim lastR as Long: LastR = Worksheets("Breaking_Data").Range("A" & Rows.Count).End(xlUp).Row
activeWS.cell("A9").Value = Application.Evaluate _
("Index(Breaking_Data!F5:F" & lastR & ", Match(A8, Breaking_Data!A5:A" & lastR & ", 0))")

You have 2 options.
You can include it as a function:
activeWS.cell("A9") = "INDEX(Breaking_Data!F5:F1048576,MATCH(A8,Breaking_Data!A5:A1048576,0))"
or you can get the value itself:
activews.Range("A9") = Application.Index(Sheets("Breaking_Data").Range("F5:F1048576"), Application.Match(activews.Range("A8"), Sheets("Breaking_Data").Range("A5:A1048576"), 0))

Related

How can I insert a dynamic last row into a formula?

I'm working with a clean sheet where I paste one column of dates with a varying number of rows. My goal is to show how many times each date shows up. However, every time I get to the last line I keep getting Run-time error '1004' Application-defined or object-defined error.
Here is my code:
Dim lastrow As Long
Set ws = ActiveSheet
Set startcell = Range("A1")
lastrow = ws.Cells(Rows.Count, "A").End(xlUp).Row
Range("B2").Formula = "=countif(A1:" & lastrow & ")"
Thanks in advance!!
COUNTIF function takes 2 arguments (https://support.microsoft.com/en-us/office/countif-function-e0de10c6-f885-4e71-abb4-1f464816df34), not one as in your code. Also missed column letter in range. If you want to process N dates, you have to make N formulas COUNTIF.
Try this code (dates in column A from A1, formulas in column B):
Sub times()
With ActiveSheet
Intersect(.Columns(1), .UsedRange).Offset(0, 1).FormulaR1C1 = "=COUNTIF(C[-1],RC[-1])"
End With
End Sub
Result:
SOLVED! 4 WAYS
High-level
Countif formula is incorrect (missing: col label A + condition)
Outlook: quick to fix, but requires loop for all dates
Current method may be CPU/time-intensive for large lists
Solutions A-D:
See Below (Links section), for google sheets (with full macro code, descriptions) for 4 solutions (3 macro based + 1 macro-free albeit dynamic soln). Briefly:
A: output with correction to your code
B: as for A, with for loop deployed
C: VB code for much quicker implementation of for loop/.Function code
D: macro-free variant (proposed/preferred)
Screenshots
Comparison table
Links:
Google Sheet
VBA count and sumifs - Automate Excel
VB code (A-C)
For completeness (same can be found in linked Google Sheet, typed - so macro-free / safe workbook):
Sub Macro_A():
lastrow = ActiveSheet.Cells(Rows.Count, "A").End(xlUp).Row
cell = Range("a4").Address
Range("B4").Value = "=countif(A1:" & "A" & lastrow & "," & cell & ")"
' For i = 1 To lastrow - Range(cell).Row + 1
' Range("B4").Offset(i - 1).Formula = "=countif(A1:" & "A" & lastrow & "," & Range(cell).Offset(i - 1).Address & ")"
' Next
End Sub
Sub Macro_B():
Application.Calculation = xlCalculationManual
start_time = Timer
lastrow = ActiveSheet.Cells(Rows.Count, "A").End(xlUp).Row
cell = Range("a4").Address
' Range("B4").Value = "=countif(A1:" & "A" & lastrow & "," & cell & ")"
For i = 1 To lastrow - Range(cell).Row + 1
Range("c4").Offset(i - 1).Formula = "=countif(A1:" & "A" & lastrow & "," & Range(cell).Offset(i - 1).Address & ")"
Next
Application.Calculation = xlCalculationAutomatic
Range("c3").End(xlDown).Offset(2).Value = Round(Timer - start_time, 2)
End Sub
Sub Macro_C():
start_time = Timer
Set Rng = Range("A4", Range("A4").End(xlDown))
For Each cell In Rng
cell.Offset(0, 3) = WorksheetFunction.CountIf(Rng, cell.Value)
Next
Range("d3").End(xlDown).Offset(2).Value = Round(Timer - start_time, 2)
End Sub
Macro-free soln (D)
Go to Formulas (ribbon), Name Manager:
In Name Manager window that apperas, click 'New...'
Populate dialogue box as req. (modifying Sheet name and $A$4 starting cell as req.)
Test your new dynamic range by clicking on upward arrow in bottom right hand corner (which should select dates in column A as depicted below)
Enter single formula in first cell of output range (here, cell D4)*:
Formulae (for convenience):
range_countif:
=Sheet1!$A$4:OFFSET(Sheet1!$A$4,COUNTA(Sheet1!$A:$A)-2,0,1,1)
Entry in cell D4
=COUNTIF(range_countif,range_countif)
*Notes: requires Office 360 for 'spill effect' (input as array formula with 'ctrl' + 'shift' + 'enter' otherwise).
Let me know if you have any further Qs. Best of luck with your excel Spreadsheet!
So many ways to achieve. I use this formula to get the number of rows
=ArrayFormula(MAX(IF(L2s!A2:A1009<>"",ROW(2:1011))))
Then I build a string from it
="L2s!A2:E"&D3
I love named ranges so I named the cell with the string built DynamicRangeL2s
Here is how I used the dynamic range in my formula (denormalize() is a custom function I wrote but could be any function) using the INDIRECT() function
=denormalize(INDIRECT(DynamicRangeL2s),INDIRECT(DynamicRangeSchedule),2,2,"right")
Here is a great article on Dynamic Ranges
https://www.benlcollins.com/formula-examples/dynamic-named-ranges/

Formatting a Formula in a String VBA

I have a script that needs to place a formula into a cell but I'm getting a 1004 error from the first part I am sure I formatted something wrong. I had difficulty with the " marks in the string but got those worked out so I'm figuring I'm missing something else. The cells are also unprotected.
Worksheets(CurSheet + 1).Range("D" & Y).Value = "=IF(D52=1,0,IF(C52=" & """Saturday""" & ",0,'" & CurSheet & "!C" & Y & "))"
This is the section that gives the error. If it is removed code works.
"=IF(D52=1,0,IF(C52="
I am not sure what I am doing wrong with this part.
It looks like you're using CurSheet as a sheet index number and as a sheet name.
The index number just returns the relative position of the sheet in the workbook while the name is what you see on the sheet tab (there's also the CodeName but I won't go into that here).
Although I don't fully understand what you're after this code will place a formula on the sheet identified with the sheet index number, so if CurSheet= 1(+1) it will place the formula on the second sheet.
The formula itself will reference the name of the sheet that is before the sheet that the formula appears on (so if the formula is on the second sheet, the formula will reference the first sheet).
Sub Test()
Dim Y As Long
Dim CurSheet As Long
Y = 1
CurSheet = 1
Worksheets(CurSheet + 1).Range("D" & Y).Formula = _
"=IF(D52=1,0,IF(C52=" & """Saturday""" & ",0,'" & Worksheets(CurSheet).Name & "'!C" & Y & "))"
End Sub
Hope I made that clear enough. :)
You need to declare that you are inputting a formula, not a value:
Change:
Worksheets(CurSheet + 1).Range("D" & Y).Value
To:
Worksheets(CurSheet + 1).Range("D" & Y).Formula

Excel VBA - Vlookup

I have two worksheets (sheet1 and sheet2). Both contain a column with header "ID" (columns are not always in the same position so need to be found).
Needed is a vlookup in a new column before the "ID" column.
This is what I got so far
sub vlookup ()
FIND COLUMNS WITH "ID"-HEADER
'Set variables for Column Sku
'note: cfind1 is for sheet 1 and cfind 2 is for sheet 2
Dim col As String, cfind1 As Range, cfind2 As Range
column = "ID"
Worksheets(1).Activate
Set cfind1 = Cells.Find(what:=column, lookat:=xlWhole)
Worksheets(2).Activate
Set cfind2 = Cells.Find(what:=column, lookat:=xlWhole)
'CREATE COLUMN WITH VLOOKUP
'activate worksheet 1
Worksheets(1).Activate
'add column before sku-column
cfind1.EntireColumn.Insert
'Select cell 1 down and 1 to left of sku-cell.
cfind1.Offset(1, -1).Select
'Add VlookUp formulas in active cell
ActiveCell.Formula = "=VLOOKUP(LookUpValue, TableArray,1,0)"
'(Lookup_Value should refer to one cell to the right
(= cfind1.Offset (1, 0)??)
'Table_Array should refer to the column in sheet(2) with header "id"
'Autofill Formula in entire column
'???
End Sub
Everything is working fine until the "vlookup-part"
I managed to put a formula in the correct cell, but I just can't get the formula to work.
How can I set lookup_value as "one cell to the right" in the same sheet
and "table_array" as the column with header "ID" in worksheet(2)?
And how can I finally autofill the vlookup formula throughout the whole column?
It would be great if anybody can help me out with the correct vlookup formula / variables and the autofilling.
You could also use something similar to below should you want to avoid using the worksheet
curr_stn = Application.WorksheetFunction.VLookup(curr_ref, Sheets("Word_Specifications").Range("N:O"), 2, False)
Valuse/variables will need to be changed of course. lookup_value,Array (range), Column number, Exact match.
Exact match needs false and similar match needs true
Try below full code
Sub t()
Dim col As String, cfind1 As Range, cfind2 As Range
Column = "ID"
Worksheets(1).Activate
Set cfind1 = Cells.Find(what:=Column, lookat:=xlWhole)
Worksheets(2).Activate
Set cfind2 = Cells.Find(what:=Column, lookat:=xlWhole)
'CREATE COLUMN WITH VLOOKUP
'activate worksheet 1
Worksheets(1).Activate
'add column before sku-column
cfind1.EntireColumn.Insert
'Select cell 1 down and 1 to left of sku-cell.
cfind1.Offset(1, -1).Select
'Add VlookUp formulas in active cell
LookUp_Value = cfind1.Offset(1, 0).Address(False, False)
Table_Array = Col_Letter(Worksheets(2).Cells.Find(what:=Column, lookat:=xlWhole).Column) & ":" & Col_Letter(Worksheets(2).Cells.Find(what:=Column, lookat:=xlWhole).Column)
ws_name = Worksheets(2).Name
Col_index_num = 1
Range_Lookup = False
ActiveCell.Formula = "=VLOOKUP(" & LookUp_Value & ", " & ws_name & "!" & Table_Array & ", " & Col_index_num & ", " & Range_Lookup & ")"
'Autofill Formula in entire column
lastrow = Range(cfind1.Address).End(xlDown).Row
Range(cfind1.Offset(1, -1).Address).AutoFill Destination:=Range(cfind1.Offset(1, -1).Address & ":" & Col_Letter(cfind1.Offset(1, -1).Column) & lastrow), Type:=xlFillDefault
End Sub
Function Col_Letter(lngCol As Long) As String
Dim vArr
vArr = Split(Cells(1, lngCol).Address(True, False), "$")
Col_Letter = vArr(0)
End Function
Haven't done this before but my approach would be to use the cell or range.formula property and build the string that you would write in the cell. for example:
myrange.formula = "=Vlookup("&Lookup_Value&","&Table_Array&","&Col_index_num&","&Range_Lookup&")"

Inserting a formula containing variable into a cell using a macro

I have a vba macro that copies the current sheet and renames it with the current date that works fine, now I want it to put a formula in cell B22, the formula that I want is:
Current Sheet Previous Sheet
='08 May 2013'!B18 - '01-04-2013'!B18
I have been trying to get this code to work, but it is putting it in as a string not a formula
i.e. = ('[08 May 2013 !R2C18] - [ 12 May 2013 !R2C18])
Dim sheet_name As String
Dim activeSheet_name As String
Dim shtName As Integer
Dim activeShtName As Integer
shtName = Sheets.Count - 1
activeShtName = Sheets.Count
sheet_name = Sheets(shtName).Name
activeSheet_name = Sheets(activeShtName).Name
Sheets(activeSheet_name).Select
Range("B22").Select
ActiveCell.Formula = " = ('[" & sheet_name & " !R2C18] - [ " & activeSheet_name & " !R2C18])"
Any help would be appreciated
Your formula is wrong. Try it in Excel first, then copy the text of the formula and compare to the text that your last line of code above is producing. Change your VBA code to this:
ActiveCell.FormulaR1C1 = "='" & sheet_name & "'!R18C2-'" & activeSheet_name & "'!R18C2"
Note the use of FormulaR1C1. Basically you need to surround the sheet names with single quotes.

Specifying cell addresses in Excel formula arguments using VBA

I have A column and B column, They compare their previous values And Iam comparing it with the following formulae
=IF((OR(AND(A2=A1,B2=B1),K2=0),0,1) it puts the 0 or 1 on the coresponding Q column
so when it goes to the 5th cell then it becames
=IF((OR(AND(A5=A4,B5=B4),K5=0),0,1)
But im trying to apply it in my VBA code like these
For numm = 2 To lastRow
Sheet1.Cells(numm, "Q").Value = ="IF(OR(AND(sheet1.cells(numm,""A"").value=sheet1.cells(numm-1,""A"")simlar way becolumn),sheet1.cells(numm,""k"").value=0),1,0)"
Next numm
But Im unable to peform the action it says 1004 error and object error
How do i use cells(numm,"A") in my VBA formulae or atleast any other way to put my formula and make it work
The reference to the looping numm within your formula needs to be out of the string.
Maybe you can set in VBA the cell formula itself...
For numm = 2 To lastRow
Sheet1.Cells("Q" & numm).Formula = _
"=IF((OR(AND(A" & numm & "=A" & numm - 1 & ",B" & numm & _
"=B" & numm - 1 & "),K" & numm & "=0),0,1)"
Next numm
Personally, I'd do the whole statement within VBA (ifs, ors, ands) and just drop the value back to Excel. Using Excel formulas makes the code harder to read.
Are you looking for something like:
Public Sub test()
Dim Sheet1 As Excel.Worksheet
Set Sheet1 = ActiveSheet
Dim numm As Integer, lastrow As Integer
lastrow = 5
For numm = 2 To lastrow
Sheet1.Cells(numm, "Q").Value = "=IF(OR(AND(" & Sheet1.Cells(numm, "A").Address & "=" & Sheet1.Cells(numm - 1, "A").Address & "," & Sheet1.Cells(numm, "B").Address & "=" & Sheet1.Cells(numm - 1, "B").Address & ")," & Sheet1.Cells(numm, "k").Address & "=0),1,0)"
Next numm
End Sub
Sheet1 can't be referred to inside the value of the cell, it only exists in the vba function you're creating, so instead you can append the strings together, and just get the cell addresses out to match the sort of function you were creating earlier.