Searching with a Macro/VBA Using a Cell reference - excel

This is probably a really easy thing that I am screwing up. I am working on a school project Creating an Inventory sheet.
My "Inventory" sheet has a bunch of product info on it.
My "Add Inventory" Sheet is set up with a VLOOKUP so when I scan my bar code it displays the row of information from the "Inventory sheet"
I made a macro button and recorded a Macro to try to edit the available inventory by clicking the button.
This is what I recorded.(the original I slaughtered trying to edit it but this should be the same)
Sub Macro7()
'
' Macro7 Macro
'
'
Sheets("Add Inventory").Select
Range("B5").Select
Application.CutCopyMode = False
Selection.Copy
Sheets("Inventory").Select
Cells.Find(What:="764666143326", After:=ActiveCell, LookIn:=xlFormulas2, _
LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False).Activate
Range("K15").Select
Sheets("Add Inventory").Select
Range("K13").Select
Application.CutCopyMode = False
Selection.Copy
Sheets("Inventory").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Range("L15").Select
End Sub
So my problem is the macro records the What:="764666143326" for the search with the bar code I was using for a sample. I need it to use the new bar code I scan on the next run. So I need it as a variable or to refence a cell. So I believe I need to set a Dim and a Range but have tried many times and watched a ton of videos with no success. I normally only use the record Macro button and don't not edit the VBA code. Please Help Me!!
EDIT:
Everying on this sheet is filled with VLOOKUP or a formula, except the yellow Cell B5, I scan the bar code into that cell.
Add Inventory sheet
This is the page I want to edit with the Macro/VBA. I want it to search column C for the Bar code number I scanned into the "Add Inventory" sheet (which will change depending on what I am adding) and when it finds the matching bar code I want it to edit the "Quantity in Stock" or column K for that row of the matching bar code.
Inventoy sheet
My problem is the macro I recorded saves what ever barcode I used for it not the cell as a variable.
Edit # 2
I think this show closer to what I am trying to do
Sub Macro7()
'
' Macro7 Macro
'
'
Sheets("Add Inventory").Select
Range("K13").Select
Application.CutCopyMode = False
Selection.Copy
Sheets("Inventory").Select
Cells.Find(What:=Range("A1"), After:=ActiveCell, LookIn:=xlFormulas2, _
LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False).Activate.Offset(0, 8).Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Sheets("Add Inventory").Select
Range("B5").Select
End Sub
For this one I made Inventory cell A1 = ='Add Inventory'!B5
Also My bar codes are 12 digits.

Update Inventory
Option Explicit
Sub addNewQuantity()
' Write lookup value (Bar Code) to a variable.
Dim lValue As Long: lValue = Range("B5").Value
' Define range (to look for Bar Code).
With ThisWorkbook.Worksheets("Inventory")
Dim fCell As Range: Set fCell = .Range("C4")
Dim lCell As Range: lCell = .Range(.Rows.Count, fCell.Column).End(xlUp)
Dim rg As Range: Set rg = .Range(fCell, lCell)
End With
' Attempt to find the index (row) of a match.
Dim cIndex As Variant: cIndex = Application.Match(lValue, rg, 0)
If IsNumeric(cIndex) Then
' Write new value to column 'K' (8 cells to the right from column 'C').
rg.Cells(cIndex).Offset(, 8).Value = Range("K13").Value
MsgBox "Bar Code ID '" & lValue & "' updated.", vbInformation, "Success"
Else
MsgBox "Bar Code ID '" & lValue & "' not found.", vbCritical, "Failure"
End If
End Sub

Unfortunately I think there is a bigger problem with this method recorded by the macro recorder - this code will always select range "K15" regardless of what you search for.
I recommend you do not use the macro recorder, among other reasons it often creates code full of semantic errors - i.e. it works and it does does exactly what you tell it to do, which may not be the same as what you want it to do! As in the example above.
I would try something like this (you will need to check that the worksheets, ranges and column numbers in the code below are correct for your project):
First we declare and assign a worksheet object, referring to your Inventory worksheet:
dim ws as worksheet
set ws = Sheets("Inventory")
Then we need to loop through every row on this worksheet and if the value in the barcode column matches a given search parameter, increase the value in the stock level column on that row, by the value of another cell on another sheet.
For this we will need a counter for the loop:
dim counter as integer
the search parameter:
dim searchParam as variant
searchParam = Sheets("Add Inventory").Range("B5").value
and the new value we want added to the current stock level:
dim newValue as variant
newValue = Sheets("Add Inventory").Range("K13").value
we need to tell Excel which column number to search in and which to change, I assumed you are adding stock to the inventory. You will need to change the column numbers below to suit your project
Dim barcodeColumnNumber As integer
Dim stockColumnNumber As integer
barcodeColumnNumber = 1
stockColumnNumber = 2
Now we add the loop
For counter = 1 To ws.UsedRange.Rows.Count
if ws.Cells(counter, barcodeColumnNumber) = searchParam then
ws.Cells(counter, stockColumnNumber) = ws.Cells(counter, stockColumnNumber) + newValue
End If
Next counter

Related

How to paste on colunm based on its name

I have this code to paste content in my table, but I want it to work correctly when I'm not in a specific cell in the current row, because it always returns a fixed cell number to paste the content, so I would like help to know how I modify this code so that it pastes the contents in the current line but instead of using ActiveCell.Offset(0, -3) , use something that would: Paste in the cell of the current row that is part of the column [Plano de Contas].
My current code:
Sub COLAR_CC()
ActiveCell.Offset(0, -3).PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=True, Transpose:=False
End Sub
Table for reference:
I think this may start you off:
Option Explicit
Sub sub1()
Dim icol&
icol = FindCol("ColTwo") ' find column
Cells(3, icol) = "Got it"
End Sub
Function FindCol&(txt$) ' find column
Dim iErr&
On Error Resume Next
FindCol = Rows(1).Find(txt, , xlValues, xlWhole, xlByColumns, xlNext, True).Column
If Err.Number <> 0 Then Stop ' handle error
On Error GoTo 0
End Function

Select Range within Row of Active Cell

I've seen several other questions similar to mine and I've tried several different solutions but I am still getting strange results. My code finds a value in another workbook in Column AA, then I want to copy that row from Column C to Column BC and paste in current workbook. All of the code works except copying from column C to BC. For some reason it starts copying the row from column AC. I've tried a standard range but I think it's relative from the active cell and I don't know if there is a way to do negative column letters so then I tried Offset and I tried .Cells but none select the correct range. Here is a couple of examples of the code I've tried:
Private Sub ComboBox1_Change()
Dim checknum As String
Dim chkrow As String
Dim Rng As Range
prfile1 = Worksheets("setup").Range("B10").Value
prfile2 = Worksheets("setup").Range("B7").Value
filepath = Worksheets("setup").Range("e10").Value
checknum = ComboBox1.Value
'Workbooks.Open filepath & prfile2
Windows(prfile2).Activate
Worksheets("MRegister").Select
With Worksheets("MRegister").Range("AA:AA")
Set Rng = .Find(What:=checknum, _
After:=.Cells(.Cells.Count), _
LookIn:=xlFormulas, _
LookAt:=xlWhole, _
SearchOrder:=xlByRows, _
SearchDirection:=xlNext, _
MatchCase:=False)
Rng.Select
.Range(.Cells(ActiveCell.Row, -24), .Cells(ActiveCell.Row, 28)).Select
Selection.Copy
End With
Windows(prfile1).Activate
Sheets("ReprintOld").Range("M203:BM203").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Application.CutCopyMode = False
Windows(prfile2).Activate
Sheets("MRegister").Range("A1").Select
ActiveWorkbook.Saved = True
ActiveWorkbook.Close
Sheets("ReprintOld").Range("A1").Select
End Sub
for Offset:
.Range(ActiveCell.Offset(0, -24), ActiveCell.Offset(0, 28)).Select
for standard Range:
.Range("C" & ActiveCell.Row & ":BC" & ActiveCell.Row).Select
You would think all of these would work, but they all start the selection several columns to the right of the active cell.
The issue is, as has been mentioned by user3561813, the fact that you have a Range object on the end of your With statement. Perhaps the simplest solution would be to use:
Intersect(Rng.Entirerow, .Worksheet.Range("C:BC")).Copy
The issue is this line: .Range(.Cells(ActiveCell.Row, -24), .Cells(ActiveCell.Row, 28)).Select
Because the With statement references With Worksheets("MRegister").Range("AA:AA"), it's trying to find the .Range property of the Column "AA".
If you rewrite it to something like Worksheets("MRegister").Range(.Cells(ActiveCell.Row, -24), .Cells(ActiveCell.Row, 28)).Select, it should work.
How about something like this after the .Find:
Rng.offset(0,3-rng.column).resize(1,53).copy
Rng is a reference to the cell with the desired checknum, offset that zero rows and back to column C, then resize it to 1 row by 53 columns (C to BC) and copy it.
You should check that the find worked before the copy:
If not rng is nothing then
You don’t need the select

Vlookup from Another Workbook with fill to Last Row

I'm looking to import data from another file (combinedWorkbook) to my master file (the file which is running the code) using a vlookup. I then need it to drag the vlookup down to the bottom row of data (using column M in the masterfile as a reference to when the data ends) with cell I15 being the starting point for the vlookup in the masterfile.
The problem I'm having is that when running the macro the vlookup is happening in cell M10 in my masterfile, not dragging down the vlookup to the end of the data and not referencing the combinedWorkbook.
Any help would be appreciated.
This is what I got so far
Dim combinedBook As Workbook
Dim filter As String
Dim caption As String
Dim combinedFilename As String
Dim combinedWorkbook As Workbook
Dim targetWorkbook As Workbook
MsgBox ("Select Unpaid Capital Extract")
Set targetWorkbook = ThisWorkbook
filter = "Text files (*.xlsx),*.xlsx"
caption = "Please Select an input file"
combinedFilename = Application.GetOpenFilename(filter, , caption)
Set combinedWorkbook = Application.Workbooks.Open(combinedFilename)
ThisWorkbook.Activate
ActiveCell.FormulaR1C1 = _
"=VLOOKUP(RC[-8],combinedWorbookSheet1!R1C1:R700000C2,2,0)"
Range("M16").Select
Selection.End(xlDown).Select
Range(Selection, Selection.End(xlUp)).Select
Range("I15:I60297").Select
Range("I60297").Activate
Selection.FillDown
Range("I15").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Copy
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Application.CutCopyMode = False
Selection.End(xlUp).Select
Range("I15").Select
combinedWorkbook.Close False
There are simply too many unknowns in your code to give a specific answer.
Some observations:
1) Always use Option Explicit at the top of your code, it will pick up mistakes and inconsistencies for you.
2) Watch out for unused variables declared in your code
3) Always specify which workbook and worksheet you are working with; don't just put Range ... or Cells.... this leads to all sorts of bugs.
4) Your VLOOKUP syntax for working with another workbook needs to be of the order
'[" & combinedWorkbook.Name & "]Sheet1'
5) xlsx are not text files btw re: your filter
6) For the rest i.e. where you want formulas to go, how you are determining last row etc I am just having to guess. Be specific when coding and try bullet pointing pseudo code first so you are clear what is going on at each stage.
Option Explicit
Sub test()
Dim filter As String
Dim caption As String
Dim combinedFilename As String
Dim combinedWorkbook As Workbook
Dim targetWorkbook As Workbook
MsgBox "Select Unpaid Capital Extract"
Set targetWorkbook = ThisWorkbook
filter = "Text files (*.xlsx),*.xlsx"
caption = "Please Select an input file"
combinedFilename = Application.GetOpenFilename(filter, , caption)
Set combinedWorkbook = Application.Workbooks.Open(combinedFilename)
'Assuming M is used to find last row in targetWorkbook
Dim lastRow As Long
With targetWorkbook.Worksheets("Sheet1") 'this wasn't specified (specify appropriate sheet name)
lastRow = .Cells(.Rows.Count, "M").End(xlUp).Row
'Assuming I is where formula is being put
.Range("I15:I" & lastRow).FormulaR1C1 = _
"=VLOOKUP(RC[-8],'[" & combinedWorkbook.Name & "]Sheet1'!R1C1:R700000C2,2,0)"
combinedWorkbook.Close False
End With
End Sub
As I understood you need to apply a vlookup formula in your master file gathering data from another workbook.
The proper strucutre is as followed:
ActiveCell.FormulaR1C1 = "=VLOOKUP(RC[8],[Book1]Sheet1!R1C5:R23C6,2,FALSE)"
The first bold text is the place of the value you are looking for, relative to the active cell.
The second bold text is the position of your reference table in your other workbook ( here it is book 1).
You can apply this formula to your masterfile by using a loop.
Dim lastRow as Integer
lastRow = ActiveSheet.Cells(ActiveSheet.Rows.Count, "M").End(xlUp).Row
endCount = 15 + lastRow
For i = 15 to endCount
ActiveSheet.Cells(i,13).FormulaR1C1 = "=VLOOKUP(RC[-8],[combinedWorkbook]Sheet1!R1C1:R700000C2,2,FALSE)"
next i
This will apply the vlookup formula in the column I starting row 15 searching for the value in the same row but 8 column before (column "A") and will apply for as many row as there are value in the column M.

Row reference in InputBox?

here's the code I currently have in VBA (Excel) at the moment. Most of it has come from macro recordings that I've made. What I'm looking for is to be able to insert for example, row 10 as just 10 in the inputbox without having to put it in as 10:10. Is there a way for me to edit my current code to allow this? I've tried using Rows("TargetRow:TargetRow") but that gives odd results.
Dim TargetRow As Variant
TargetRow = InputBox("Insert row # where data should be inserted. This should take the format XX:XX (e.g. 90:90 for row 90)", "All Industries Row", "XX:XX")
wbThis = ThisWorkbook.Name
Windows(wbThis).Activate
Rows(TargetRow).Select
Selection.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromAbove
Windows("otherworksheet.xlsx").Activate
Range("A119:J119").Select
Application.CutCopyMode = False
Selection.Copy
Windows(wbThis).Activate
Range(TargetRow).Select
Selection.PasteSpecial Paste:=xlPasteValuesAndNumberFormats, Operation:= _
xlNone, SkipBlanks:=False, Transpose:=False
Application.CutCopyMode = False
Use following sub to select rows using inputbox
Sub SelectRow()
Dim lnRow As Long
lnRow = InputBox("Enter Row number.", "Row Input")
Rows(lnRow & ":" & lnRow).Select
End Sub
If you need a Range from user input, the simplest way is to use the Excel version Application.InputBox with a type of '8' (see the documentation here).
Dim TargetRow As Range
Set TargetRow = Application.InputBox("Select the row where data should be inserted.", _
"All Industries Row", , , , , , 8)
Debug.Print TargetRow.Address
Note that you should probably also get rid of the Select and Activate calls and use your object references directly.

Adding Pivot Values - further issues

I am attempting to add VLookups into a worksheet using VBA. I have managed to get my code sort of working with the help of this group but there are still errors as outlined below.
1st VLOOKUP in Column AA
Typed formula would look : =VLOOKUP(B2,'Supplier Audit Report'!C:AB,26,FALSE)
2nd VLOOKUP in Column BB
Typed formula would look : =VLOOKUP(U2,Pivot!A1:B1802,2,FALSE)
Where the cells A1:B1802 is a pivot table defined as pvt
(the size of the pivot will be different every time the macro is run so I would prefer to reference to the defined pivot table rather then A1:B1802)
I want the formula to be filled down to the end of the data in the table (again this will be to a different cell each time.
My code is as follows. I have gone through various iterations and this iteration succeeds in getting a VLOOKUP formula into AA, but not AB. However, the formula is as follows in EVERY cell of the column (i.e. the xcell reference is not changing as the formula loops and as it is text with no " " around it, it isn't bringing back a value.)
=VLOOKUP(SEUR0310,'Supplier Audit Report'!C:AB,26,FALSE)
Where SEUR0310 isn't even the value in B2. I want the formula to display:
=VLOOKUP(B2,'Supplier Audit Report'!C:AB,26,FALSE) in cell AA2
=VLOOKUP(B3,'Supplier Audit Report'!C:AB,26,FALSE) in cell AA3 and so on
When it finishes the first loop for AA, I get an error for the AB Vlookup as follows: Application-defined or object defined error. Run-time error 1004.
Does anyone have any advice on how to fix the code to get this to work. I am still exceptionally new to VBA so all your help is very much appreciated.
Current Code
Sub Adding_VLOOKUPS()
Dim pvt As PivotTable
Dim sAP As Worksheet
Dim sDB As Worksheet
Dim sSAR As Worksheet
Dim lastrow As Long
Dim rMT As String
Dim rPO As String
Dim xcell As Variant
Dim ycell As Variant
Set sAP = Sheets("AP Invoice Lines")
Set sDB = Sheets("DashBoard PO Report")
Set sSAR = Sheets("Supplier Audit Report")
Set pvt = Sheets("Pivot").PivotTables("PivotTable1")
lastrow = sAP.Cells(Rows.Count, "B").End(xlUp).Row
rMT = "AA2:AA" & lastrow
rPO = "AB2:AB" & lastrow
Range("AA1").Select
ActiveCell.FormulaR1C1 = "Matching Type"
Range("AB1").Select
ActiveCell.FormulaR1C1 = "PO Value"
Columns("Y:Y").Select
Selection.Copy
Columns("AA:AB").Select
Selection.PasteSpecial Paste:=xlPasteFormats, Operation:=xlNone, _
SkipBlanks:=False, Transpose:=False
Application.CutCopyMode = False
For Each xcell In sAP.Columns("B").Cells.SpecialCells(xlCellTypeConstants)
Range(rMT).Formula = "=VLOOKUP(" & xcell & ",'Supplier Audit Report'!C:AB,26,FALSE)"
Next xcell
For Each ycell In sAP.Columns("U").Cells.SpecialCells(xlCellTypeConstants)
Range(rPO).Formula = "=VLOOKUP(" & ycell & ",'Pivot'!A1:B1802,2,FALSE"
Next ycell
End Sub
A couple of things when reading through the code:
1) I'm not sure you need to write rmt = "AA2:AA". It might be enough to write rmt = "AA"
Range("AA1").Select
ActiveCell.FormulaR1C1 = "Matching Type"
Range("AB1").Select
ActiveCell.FormulaR1C1 = "PO Value"
Columns("Y:Y").Select
Selection.Copy
Columns("AA:AB").Select
Selection.PasteSpecial Paste:=xlPasteFormats, Operation:=xlNone, _
SkipBlanks:=False, Transpose:=False
Application.CutCopyMode = False
Why do you need this code block? It looks like you are making column labels that don't really have anything to do with putting the formula in the columns.
Also, in the for each loop you need a next statement to end the loop. This way excel knows when to iterate the cell; to go from one cell to the next cell. The work on each cell is done within the loop, but the loop needs an opening (for each cell in range) and a closing (next)
Are you looking for an explanation on how those methods work? (IE how the loop works or how the range method works?)

Resources