VBA Referring to a cell using Sheet Name not working properly - vba

Summary: I am writing a macro that takes names from many different sheets in an excel file and compiles them together on a "master list", but I'm having trouble with referencing a cell on another sheet.
The Problem: When I refer to a specific cell using the sheet name as reference with Sheets("MasterList").ActiveCell.Offset(0, 1), nothing gets picked up. However, when I remove Sheets("MasterList") the macro works fine (the macro is currently on "MasterList" at the time which is the only way this would work). Also, the spelling for the name of the sheet was correct in my code.
Question: Why is this happening? The logic behind the code seems sound, and I'm spelling my sheet name correctly.
Code:
Do
If Sheets("MasterList").ActiveCell.Offset(0, 1) = firstName Then 'IF FIRST AND LAST NAMES MATCH, EXIT THE CHECK
Exit Do
End If
On Error Resume Next
Cells.Find(What:=lastName, After:=ActiveCell, LookIn:=xlFormulas, _
LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False).Activate
Loop Until Err.Number > 0

ActiveCell is a property of the Application object, not a Sheet.
There is only one ActiveCell, and it is the active cell on the currently active sheet.
It's not entirely clear what you are trying to do. But in general you should avoid Select and Activate with this sort of code. Use instead somthing like:
Dim wsMasterList as Worksheet
Set wsMasterList = Thisworkbook.WorkSheets("MasterList") ' assuming the vba code is in the workbook containing MasterList
To track the last used cell in MasterList use a variable like
Dim rMasterList as Range
Set rMasterList = wsMasterList.Cells( ... ' Specify the cell you want
Then use rMasterList.Offset(0, 1) to refer to cells relative to that cell
Searching on MasterList use:
Dim cl as Range
Set cl = wsMasterList.UsedRange.Find( ... )
If Not cl Is Nothing Then
' cl will be Nothing if the search term is not found
' ...

Related

Run time error 91, Object variable or with block variable not set, lastrow [duplicate]

What I want:
I've got a lot of sheets whith different devices. Let's call one of these sheets "WS1".
And I've got a seperate sheet with all existing devices and the appropriate OS next to it. This one we call "list".
Now I want the other sheets (e.g. the "WS1") to check the "list", find the right device, and copy the right OS into the WS1-sheet.
the manual way would be:
select cell "C3" of WS1 and copy it.
open the "list"-Sheet and find the copied entry
select the cell left to the found entry and copy it
open the WS1 again, select the left cell right next to the active cell and paste the new clipboard (which contains the OS)
select the next cell which is under and on the right side of the active cell.
loop until every device in WS1 is filled with an OS
What I've got so far:
Dim DataObj As New MSForms.DataObject
Dim strCliBoa As String
'strCliBoa = DataObj.GetText
DataObj.GetFromClipboard
Range("C3").Select
Selection.Copy
strCliBoa = DataObj.GetText
Sheets("list").Select
Range("A1").Select
Cells.Find(What:=strCliBoa, After:=ActiveCell, LookIn:=xlFormulas, _
LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=True, SearchFormat:=False).Activate
ActiveCell.Offset(0, -1).Select
Selection.Copy
strCliBoa = DataObj.GetText
Sheets("WS1").Select
ActiveCell.Offset(0, -1).Select
ActiveSheet.Paste
ActiveCell.Offset(1, 1).Select
My issue:
"Runtime Error 91: Object variable or with block variable not set"
and it marks the cells.find-method.
Can someone tell me what I'm doing wrong?^^
Thanks in advance!
(oh, almost forgot: I'm using ms excel 2010 on Win7)
If the string you're looking for isn't found you'll get that error. The find function returns "Nothing" if nothing is found
Dim r As Range
Set r = Cells.find(What:=strCliBoa, After:=ActiveCell, LookIn:=xlFormulas, _
LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=True, SearchFormat:=False)
If r Is Nothing Then
'handle error
Else
'fill in your code
End If
I'll provide you an answer using the VLOOKUP() function. So Sheet1 contains several devices and I need to find the correct OS. Sheet2 contains the matching between device and OS.
On Sheet1 enter this formula in the cell next to device and pull it down (of course edit to your specific needs).
=VLOOKUP(A2;Sheet2!$A$1:$B$20;2;0)
EDIT: the VLOOKUP function will only work if the OS is in second column. Either switch around the columns or use a helper column at the end to contain the OS.
In the sheet where you have the Device name (WS1) put formula:
=INDEX(List!$A$2:$B$10;MATCH('WS1'!C3;List!$B$2:$B$10;0);1)
Where :
List!$A$2:$B$10 is a range where you have the Devices + OS in the list
'WS1'!C3 is the Device you want to search for in the list ("WS1" in your case)
List!$B$2:$B$10 is the column on Sheet List, where the devices are listed.
Edit 1 - VBA code
If you want to use VBA then use this :
Sub FindDevicePasteOS()
'Find corresponding OS for the device
Dim intRow As Integer
Dim wsht As Worksheet
For Each wsht In Worksheets
If wsht.Name <> "List" Then 'add more sheets you want to exclude using OR (e.g. ... Or wsht.Name <> "Cover Sheet" Then)
For intRow = 3 To wsht.Cells(Rows.Count, 3).End(xlUp).Row 'presuming there is nothing else in the column C below the devices
If Not Worksheets("List").Cells.Find(what:=wsht.Cells(intRow, 3)) Is Nothing Then
wsht.Cells(intRow, 2) = Worksheets("List").Cells.Find(what:=wsht.Cells(intRow, 3)).Offset(0, -1)
End If
Next intRow
End If
Next wsht
End Sub
So I used a psuedo solution where I added the If x is nothing block to the code to skip over the err'd pieces. I was able to process about 80% of the data which is good for me. I still can't understand why Find would return nothing.
Another interesting and maybe related problem occurred in a different computer running the same macro - after I ran into this problem a few times, my computer gave me a blue screen with a 'thread stuck in driver' message. Could they be related? Excel processing to much to fast and get's mixed in the thread processing?
Food for though, I dunno why the find won't just work every-time.
In Sobigen post I had to switch the part LookAt:=xlPart to LookAt:=xlWhole to get it to work because If r Is Nothing Then was throwing an error when it found partial matches. Other than that the code worked great thanks!

Lookup in all the sheets for specific text and if match then write value of same row but different column value to master sheet

check over all sheets
If specific text (e.g., yes) is found in the fifth row of a sheet, get data from that row (but different column) and write data to a master sheet
How can I do that?
I found below code relatively useful for me but, not 100% matching with my requirement. please help me on this.
Problem in this code is:- i have specific text(yes) in specific range(e6:e16).
What I want is to check for only yes word. If found then write value of column A & row, in which yes word found, into master sheet and check it till last sheet.
Sub SeachSheets()
Dim FirstAddress As String, WhatFor As String
Dim Cell As Range, Sheet As Worksheet
WhatFor = InputBox("What are you looking for?", "Search Criteria")
If WhatFor = Empty Then Exit Sub
For Each Sheet In Sheets
If Sheet.Name <> "SEARCH" Then
With Sheet.Columns(1)
Set Cell = .Find(WhatFor, LookIn:=xlValues, LookAt:=xlPart)
If Not Cell Is Nothing Then
FirstAddress = Cell.Address
Do
Cell.EntireRow.Copy _
Destination:=Sheets("SEARCH").Range("A" & Rows.Count).End(xlUp).Offset(1, 0)
Set Cell = .FindNext(Cell)
Loop Until Cell Is Nothing Or Cell.Address = FirstAddress
End If
End With
End If
Next Sheet
Set Cell = Nothing
End Sub
Any help will be appreciated.
Thank you.
For one sheet, this is easy to accomplish with a formula alone, e.g.
= INDEX(1:1,MATCH("yes",5:5,0))
This finds the first instance of yes in the 5th row of the current sheet, and returns the value in 1st row and in the same column.
One option is to have this formula above somewhere on each sheet in your workbook as a "helper cell" (e.g. cell Z99) and then have a formula somewhere on your master sheet to check all of these helper cells, e.g.
= IFERROR(Sheet1!Z99,IFERROR(Sheet2!Z99,IFERROR(Sheet3!Z99,IFERROR(...,"no match"))))
Of course, also possible without helper cells at all, but the formula just gets messy:
= IFERROR(INDEX(Sheet1!1:1,MATCH("yes",Sheet1!5:5,0)),
IFERROR(INDEX(Sheet2!1:1,MATCH("yes",Sheet2!5:5,0)),
IFERROR(INDEX(Sheet3!1:1,MATCH("yes",Sheet3!5:5,0)),
IFERROR(...,"no match"))))
If you want a way without explicitly calling each sheet, then VBA is probably required. Just posting a solution without VBA to see if this will work for you.

Find email adresses in excel workbook

I have a excel sheet which containts an emails in exact one column(the order of the column is not exact and changing).
I used the find function looking like this.
Sub emialy()
Cells.Find ("#",,xlValues,xlPart,xlByRows,,,,) ActiveCell.Copy
End Sub
but I am recieving an error...
Then if a program finds where the emails list are beginning i want to copy that very first email and open an email client (outlook), create an new email and paste the exact copied email to the "to:" row.
The recommended way to use the Find function, is by setting a Range type variable to the result. This way you can trap the scenario Find was unable to find # throughout your worksheet's Cells with If Not EmailRng Is Nothing Then.
Code
Sub emialy()
Dim EmailRng As Range
Set EmailRng = Cells.Find(What:="#", LookIn:=xlValues, Lookat:=xlPart, SearchOrder:=xlByRows)
If Not EmailRng Is Nothing Then ' succesful find
EmailRng.Copy
Else
MsgBox "Could not find the # symbol"
End If
End Sub

How to expand a group in Excel by using Hyperlink(or by maybe assigning Macro to Hyperlink)

I have a table at the top of my sheet and this table has a different section names.
I'd like to insert a hyperlink to these section names to go and open it's group below when I click them.
Please Refer to the view of my table and sections as default (Collapsed)
I could create a macro which:
Expands all groups
Goes to the Section that I clicked,
Collapses all groups
Only opens the group on active cell,
But assigning this macro to ~20 different sections increases the file size.
After some search I found this on SO: Excel: Assign a macro to a hyperlink? So maybe there is a way to connect this two method?
How this can be solved?
I'd suggest creating a master sheet with the "group" table and any rollups you need. The subsequent sheets could have all the "section" data on them. This has the added benefit of being more scaleable.
Is it strictly necessary to have all the information on the same sheet? This is pretty much why Excel has multiple sheets. Using multiple sheets would also allow you to use standard hyperlinks.
However, if you would like some VBA to get you closer, consider the code below. This grabs the value form the active cell, then searches for the next cell with that value. If the section with the found cell is collapsed, it expands it and visa versa.
Sub OpenSection()
Dim x As String
x = ActiveCell.Value
Dim y As String
y = Cells.Find(What:=(x), After:=ActiveCell, LookIn:=xlFormulas, _
LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False).Address
'Range("b1").Value = y
With ActiveSheet
With .Range(y).EntireRow
If .ShowDetail = False Then
.ShowDetail = True
Else
.ShowDetail = False
End If
End With
End With
End Sub

Find a value from one worksheet in a designated range in another

Intent
It will consist of 11 identical Worksheets (10 for data entry specific areas of the site being worked on, and 1 "Master" which gathers the totals)
The Master Worksheet is where the Start Date is changed. When the Start Date is changed it is reflected in the 10 data entry Worksheets. There are numeric values as well showing how far away the Start Date is.
When the Start Date is changed, the values need to move with the Start Date (i.e. if the Start Date is January 5 and there is already data on the data entry worksheets, if the Start Date is changed to January 7 then all data on all worksheets will need to move to the right by 2)
Intended Process
I was able to get the first two functions working, however it's the last one that's causing some grief.
What I had in mind was a procedural copy-paste of sorts. When the Start Date is changed it would go to the first data entry worksheet and copy the current header settings to a "Transfer" Worksheet, preserving the original date settings for that worksheet. It would then delete the data in the data entry worklist.
The next step was to go to the first of the data entry Worksheets (Codenames in the background start with "Sz"), match the first numeric value of the data entry to the Transfer worksheet, retrieve the data and paste the column data into it's new location.
When it's all done with the data entry worksheet it would then clear out the "Transfer" worksheet, move to the next data entry worksheet, and repeat the process.
Problem
Unfortunately, the code I have written is saying it is finding the numeric values, when that numeric value doesn't exist. And then it sometimes has an error message stating "Code execution has been interrupted".
I have been working on this for about fifteen hours overtime, in addition to about a full week. I have googled countless potential solutions, and tried many workarounds, but am officially at a dead end. I have mostly taught myself through other people's examples, so I'm not an expert in Excel VBA.
If I can get the matching functions working correctly, I believe I should be able to handle the rest, but suggestions on more efficient methods are more than welcome.
I don't use Forums much, but I'll try to paste the code below.
Please let me know what other information I could provide.
Edit: Here is the sample of the Workbook. To run the function you will need to be on the "Plant" worksheet (Sz001): Dropbox Link
Code:
Sub Test()
Dim sh As Worksheet, flg As Boolean
For Each sh In Worksheets
'FUNCTIONAL: If sh.CodeName Like "Sz0*" Then 'flg = True
If sh.CodeName = "Sz001" Then 'Isolating a single Worksheet for testing
'Copy original values and location to Transfer Worksheet
'DISABLED THIS SECTION WHILE TESTING
'sh.Select
'ActiveSheet.Range("H8:ABI460").Copy
'Worksheets("Transfer").Select
'ActiveSheet.Range("H8").PasteSpecial xlPasteValues
'Begin Matching Loop -THIS IS WHERE THE ISSUES ARE HAPPENING
Dim xlRange As Range 'Current sh Range
Dim xlSheet As Worksheet 'Current sh Worksheet
Dim xlCell As Range 'Cell function is currently looking at
Dim x As Range
Set xlSheet = sh
Set xlRange = xlSheet.Range("H6:ABI6")
For Each xlCell In xlRange
Set x = ActiveSheet.Cells.Find(what:=xlCell, after:=Worksheets("Transfer").Range("G6"), LookIn:=xlValues, LookAt:=xlWhole, SearchOrder:=xlByColumns, SearchDirection:=xlNext)
If Not x Is Nothing Then
MsgBox Cells(xlCell.Row, xlCell.Column) & "Found"
Else
MsgBox Cells(xlCell.Row, xlCell.Column) & "Not Found"
End If
Next xlCell
End If
Next
End Sub
Tested:
Option Explicit
Public Sub Test()
Const WS_TR As String = "Transfer" 'Sheet Transfer
Const WS_RNG As String = "H6:ABI6" 'row 6 on both sheets
Dim wsSz As Worksheet, wsTr As Worksheet, cel As Range
Dim found As Range, row6Sz As Range, row6Tr As Range
Set wsSz = Sz001 'Code Name for the sheet "Sz001"
Set wsTr = Worksheets(WS_TR)
Set row6Sz = wsSz.Range(WS_RNG) 'searched values
Set row6Tr = wsTr.Range(WS_RNG) 'search area
For Each cel In row6Sz 'searched values
Set found = row6Tr.Find(what:=Val(cel.Value2), LookIn:=xlValues, _
LookAt:=xlWhole, SearchFormat:=False, _
SearchOrder:=xlByColumns, SearchDirection:=xlNext)
Debug.Print cel.Value2 & IIf(Not found Is Nothing, " Found", " Not Found")
Next
End Sub
.
Note:
I replaced the MsgBox with Debug.Print
For results press Ctrl+G, or View -> Immediate Window