I have a workbook that has 4 different sheets for inventory purposes (each sheet corresponds to a type of inventory to make organizing easier). Not the best setup, but I have a barcode lookup system where I scan the item's barcode and Excel finds and highlights the corresponding row (containing info like name, picture, quantity, etc.) that's all updated manually. Originally everything was on one sheet but recently I have sorted them out into 4 different sheets. Since then the barcode lookup only works on the original inventory sheet (makes sense since the code was only for that one sheet). I have been unable to figure out how to change the code to work on the whole workbook. I have tried to change worksheet to workbook (didn't work), then I tried to add a Set ws = ThisWorkbook.Sheets("") for each sheet (also didn't work) and a handful of other changes. If anyone has any idea on how to change it so it searches the workbook instead of the one sheet I would appreciate it.
Here is a copy of the working code for the first sheet:
Private Sub CommandButton1_Click()
Dim ws As Worksheet
Set ws = ThisWorkbook.Sheets("Inventory List")
Dim rangeToLook As Range
Set rangeToLook = ws.Range("C3:C1000")
Dim wholeRange As Range
Set wholeRange = rangeToLook.Resize(, 10)
' change 14408667 to yours grey color code here
wholeRange.Cells.Interior.Color = 14408667
Dim code As Variant
code = InputBox("Please scan a barcode and hit enter if you need to")
Dim matchedCell As Range
Set matchedCell = rangeToLook.Find(what:=code, LookIn:=xlValues, _
lookat:=xlWhole, MatchCase:=True)
If Not matchedCell Is Nothing Then
With matchedCell
Application.Goto .Cells(1)
.Resize(1, 10).Interior.ColorIndex = 20
End With
Else
MsgBox "Barcode Not Found"
End If
End Sub
Thank you for the help in advance.
Try this code:
Private Sub CommandButton1_Click()
Dim ws As Worksheet
Dim rangeToLook As Range
Dim wholeRange As Range
Dim code As Variant
Dim matchedCell As Range
code = InputBox("Please scan a barcode and hit enter if you need to")
For Each ws In ThisWorkbook.Sheets
Set rangeToLook = ws.Range("C3:C1000")
Set wholeRange = rangeToLook.Resize(, 10)
wholeRange.Interior.Color = 14408667
Set matchedCell = rangeToLook.Find(what:=code, LookIn:=xlValues, _
lookat:=xlWhole, MatchCase:=True)
If Not matchedCell Is Nothing Then
With matchedCell
Application.Goto .Cells(1)
.Resize(1, 10).Interior.ColorIndex = 20
Exit For
End With
End If
Next
If matchedCell Is Nothing Then
MsgBox "Barcode Not Found"
End If
End Sub
Related
I am new to VBA and have cobbled this together from code I found in forums and the code generated by a recorded macro. I think it is close, but there is one issue I cannot figure out after much searching. Your help is appreciated.
I have a Worksheet in wb1 with a Value in cell B3, and I want to search for that value in wb2 (across multiple sheets). When the value is located, I want to select a range of cells in the worksheet where the value was found and then copy that back to wb1.
The code successfully finds the value in wb2. It selects a range of cells and copies it back to wb1. The problem is that it does not select the cells from the desired worksheet (where the value was actually found). It selects the range of cells from whichever sheet wb2 was opened to. For example, if Excel opened wb2 to Sheet1, and my Value is found in Sheet3, it still copies the range from Sheet1.
I need it to find the cells in a Sheet, and then copy from that Sheet. This is what I have so far (I have a couple of message boxes to see if the code was correctly looping through the sheets and finding something):
Sub PasteTemplate()
Dim wb1 As Workbook
Set wb1 = ThisWorkbook
Dim Dest As Worksheet
Set Dest = ActiveSheet
Dim FindValue As String
FindValue = Range("B3").Value
Dim PasteHere As Range
Set PasteHere = Range("A5")
'This section opens wb2 if it is not already open
Dim fStatus As Long
Err.Clear
On Error Resume Next
Set wb2 = Application.Workbooks.Open(filename:="Templates.xlsx", UpdateLinks:=False)
fStatus = Err
On Error GoTo 0
If fStatus Then
Set wb2 = Application.Workbooks.Open(filename:="Templates.xlsx", UpdateLinks:=False)
End If
Dim FoundValue As Range
For Each Sheet In wb2.Sheets
With Sheet.Columns("B")
Set FoundValue = .Find(What:=FindValue, LookIn:=xlValues, _
LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=True, SearchFormat:=False)
If FoundValue Is Nothing Then
msgbox "Value not found in " & Sheet.Name
End If
If Not FoundValue Is Nothing Then
msgbox "Found the value in " & Sheet.Name
Range("A1:Z100").Select '//Where the problem is. It selects the range in the sheet where wb2 was opened to
Application.CutCopyMode = False
Selection.Copy
End If
End With
Next
wb1.Activate
PasteHere.Select
ActiveSheet.Paste
End Sub
Just having Range(). is the same as having ActiveSheet.Range(). So it's always good to specify the sheet. This goes for the variables as well, like PasteHere
Also, the obligatory link to how to avoid using select.
Can't test it, but maybe something like this:
Since you are using a for each loop, we have the current sheet as a variable ready to use when referring to the range.
...
For Each Sheet In wb2.Sheets
With Sheet.Columns("B")
Set FoundValue = .Find(What:=FindValue, LookIn:=xlValues, _
LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=True, SearchFormat:=False)
If FoundValue Is Nothing Then
msgbox "Value not found in " & Sheet.Name
End If
If Not FoundValue Is Nothing Then
msgbox "Found the value in " & Sheet.Name
Sheet.Range("A1:Z100").Copy PasteHere
End If
End With
Next
End Sub
Developing a code through which user selects a range in the active workbook. For the range selected i.e. A8:A12 i want to run a loop through which for each range in the selected range, the loop takes its value, Filters GL_Sheet's Current Region (GL_Rng) using that value and copy's the visible cells
The code is
'Declaring Workbooks
Dim GL_CY As Variant
Dim GL_Book As Workbook, Tgt_Book As Workbook
GL_CY = Application.GetOpenFilename(Title:="Open GL", FileFilter:="Excel Files (*.xls*),*xls*")
Set GL_Book = Application.Workbooks.Open(GL_CY)
Set Tgt_Book = Workbooks.Add
'Selecting Range
Dim GL_Code As Variant, GL_LR As Long, GL_Rng As range, Rng As range
Dim GL_Sheet As Worksheet, tgt As Worksheet
Set GL_Sheet = GL_Book.Worksheets(1)
GL_LR = GL_Sheet.range("B" & Rows.Count).End(xlUp).Row
Set GL_Rng = GL_Sheet.range("A4:R" & GL_LR).CurrentRegion.Offset(3, 0)
GL_Code = Application.InputBox(Prompt:="Select the range of GL codes to generate its GL activity ", Title:="Generate GL Activity", Type:=8)
' GL_Sheet.range("A3:A5").Value = range(GL_Code).Value
For Each Rng In range(GL_Code)
Set tgt = Tgt_Book.Worksheets.Add
GL_Rng.AutoFilter Field:=6, Criteria1:=GL_Code
GL_Rng.SpecialCells(xlCellTypeVisible).Copy
tgt.Paste
tgt.range("A1").CurrentRegion.Cut tgt.range("B6")
tgt.Cells.WrapText = False
tgt.Cells.Columns.AutoFit
tgt.Name = GL_Code
Application.CutCopyMode = False
Next Rng
As you can see I am struggling with the last part of the code which results in Error 1004 (Method of range...)
Naqi,
I created a little test routine to check out what was being returned from the InputBox.
Turns it was coming back as a Variant. I tried setting it as a Range but that wouldn't work either. However changing the Type:=2 (string) makes it work
Option Explicit
Sub Test()
Dim GL_Code As String
GL_Code = Application.InputBox(Prompt:="Select the range of GL codes to generate its GL activity ", _
Title:="Generate GL Activity", _
Type:=2)
Debug.Print Range(GL_Code).Address()
End Sub
'So by changing your Type to 2 the For Each rng statement should no longer create a problem.
Edit: Found an option using Type 8:
[Click here for the post I found this in.][1]
Sub MyMacro()
Dim GL_Code As Range
Set GL_Code = Application.InputBox("Select a range", "Get Range", Type:=8)
Debug.Print GL_Code.Address()
End Sub
'Since GL_Code is now a range your For Each should NOT enclose it in a Range() function!
HTH
I'm currently doing VBA project which need to copy from a workbook to another, which the WBookPst is the workbook I firstly open (use) meanwhile WBookCopy is the workbook where I open based on the links where I got by listing all ".xslt" format in a File into my Sheet1 of my first workbook. Here is my code :
Sub SortFiles()
'Set up your variables and turn off screen updating.
'Dim iCounter As Integer
Application.ScreenUpdating = False
'Sort the rows based on the data in column C
Columns("A:C").Sort key1:=Range("C2"), _
order1:=xlDescending, Header:=xlYes
Application.ScreenUpdating = True
Dim WBookCopy As Workbook
Dim WBookPst As Workbook
Dim filePath As String
Dim sheetName As String
Dim sheetCopy As Worksheet
Dim sheetPate As Worksheet
Dim rngCopy As Range
Dim rngPst As Range
filePath = Range("B2").Value
Set WBookCopy = Workbooks.Open(filePath)
Columns(30).Insert
For i = 1 To Sheets.count
Cells(i, 30) = Sheets(i).Name
Next i
sheetName = Range("AD1").Value
Set sheetCopy = WBookCopy.Worksheets(sheetName)
Set rngCopy = sheetCopy.Range("A:AA").Copy
Set WBookPst = ThisWorkbook
Set sheetPaste = WBookPst.Worksheets("Sheet1").Activate
Set rngCopy = sheetPaste.Range("A:AA").Select
ActiveSheet.Paste
End Sub
At Set rngCopy = sheetCopy.Range("A:AA").Copy there's error "Objects required".
What does that mean?
By the way, is how I copy and paste the data between sheets correct?
The issue is that rngCopy is of type range and you can't set it equal to a method (copy). Remove the .Copy and you should be fine. You also don't need to set the worksheet out range to a variable. You could just do one line that says WBookCopy.SheetName.Range("A:AA").Copyand then another line to paste.
As #Wyatt mentioned - your copy\paste syntax is incorrect
Here are 2 ways to do it:
Worksheets("Sheet1").Range("A:AA").Copy
Worksheets("Sheet2").Range("A1").PasteSpecial xlPasteAll
or
Worksheets("Sheet1").Range("A:AA").Copy Destination:=Worksheets("Sheet2").Range("A1")
I'm trying to write some code to transfer large amounts of user selected data from one open workbook to another. The number of rows/columns varies and the starting point in the destination workbook also varies.
I get a debug Run-time error '13': Type mismatch on the last line of code. There's probably a more elegant way to do some things like size the destination range, but everything else seems to be working as expected.
Public SourceWorkbook As Workbook
Public SourceWorksheet As Worksheet
Public DestWorkbook As Workbook
Public DestWorksheet As Worksheet
Public selectedRange As Range
Public selectedRows As Long
Public selectedColumns As Long
Sub SelectRange()
Set SourceWorkbook = ActiveWorkbook
Set SourceWorksheet = ActiveSheet
'Display the Input Box to make selection
On Error Resume Next
Set selectedRange = Application.InputBox( _
Prompt:="Select the range of cells you want to copy.", _
title:="Select Range", _
Default:=ActiveCell.Address, _
Type:=8)
' Was the Input Box canceled?
If selectedRange Is Nothing Then
MsgBox "Cancelled"
Exit Sub
End If
selectedRange.Select
'Set row and column number variables
selectedRows = Selection.Rows.Count
selectedColumns = Selection.Columns.Count
'vbModeless Form that allows user to select another open workbook and start cell. The OK button simply calls the MoveData sub.
SwitchWorkbooksForm.Show vbModeless
End Sub
Sub MoveData()
Dim DestRange As Range
Set DestWorkbook = ActiveWorkbook
Set DestWorksheet = ActiveSheet
'Start the desination range at the user select cell and Set it to the same size as the originally selected range
StartRow = ActiveCell.Row
finalRow = StartRow + selectedRows - 1
StartColumn = ActiveCell.Column
finalColumn = StartColumn + selectedColumns - 1
Range(Cells(StartRow, StartColumn), Cells(finalRow, finalColumn)).Select
Set DestRange = Selection
'Debug error on the next line
Workbooks(DestWorkbook).Worksheets(DestWorksheet).Range(DestRange).Value = _
Workbooks(SourceWorkbook).Worksheets(SourceWorksheet).Range(selectedRange).Value
End Sub
You are using the Workbooks(...) and Worksheets(...) collections by passing in workbook and worksheet objects. You should be passing in names or using the workbook and worksheet references you've assigned directly.
Workbooks(DestWorkbook.name).Worksheets(DestWorksheet.name).Range(DestRange.address).Value = _
Workbooks(SourceWorkbook.name).Worksheets(SourceWorksheet.name).Range(selectedRange.address).Value
... or,
DestRange = selectedRange.Value
You do not have to keep redefining the parents of a range object you have Set.
I have two sheets in a workbook. 1st sheet name is “summary” and another is “target”.
I have chart in summary tab. I want to set the source data for that chart to target tab that contains date. Ex(11/01/2013 – 11/30/2013).
Everyday I want to change the chart date for corresponding date. So I tried in excel vba as below:
sheets("Summary ").Select
ActiveSheet.ChartObjects("Chart 3").Activate
ActiveChart.PlotArea.Select
Sheets("Target").Select
a = InputBox("enter the date - format(mm/dd/yyyy)")
Set findrow = Range("a:a").Find(what:=a, LookIn:=xlValues, LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False).Rows
findrownumber = findrow.Row
ActiveChart.SeriesCollection(2).Values = "='Target Chart'!R4C78:R" & findrownumber & "C78"
End sub
While I am trying to enter source data value in formula it shows error.
Please help me.
This is the code that I tried and it works. I might have switched the names of the sheet while creating this example but you can change that in the code :)
Let's say the Summary Tab looks like this
And your Chart in Target Sheet looks like this at the moment. The source data is set to =Summary!$A$1:$A$6
Now Try this code
Option Explicit
Sub Sample()
Dim wsSum As Worksheet, wsTgt As Worksheet
Dim objChart As ChartObject, chrt As Chart
Dim sDate
Dim findrow As Long
Dim aCell As Range
'~~> Accept the date
sDate = InputBox("enter the date - format(mm/dd/yyyy)")
'~~> Check if user entered something
If sDate <> "" Then
'~~> Set your respective worksheets
Set wsSum = ThisWorkbook.Sheets("Summary")
Set wsTgt = ThisWorkbook.Sheets("Target")
'~~> Find the date in the cell
With wsSum
For Each aCell In .Columns(1).Cells
If Format(aCell.Value, "mm/dd/yyyy") = sDate Then
'~~> Get the row number
findrow = aCell.Row
Exit For
End If
Next aCell
End With
'~~> Update the chart
With wsTgt
Set objChart = .ChartObjects("Chart 1")
Set chrt = objChart.Chart
chrt.SeriesCollection(1).Values = "='Summary'!R4C1:R" & findrow & "C1"
End With
End If
End Sub
When you run the code, in the Inputbox, set the date as "01/11/2013"
And this is the output which you will get with source data set as =Summary!$A$4:$A$11
IMPORTANT: I wouldn't recommend using Inputbox for capturing a date. You might want to use THIS