Using Find method to search for a string from another worksheet - vba

Perhaps I just haven't used the right search terms, I am still new to VBA, but I just can't find the solution to my problem:
I am trying to find a value (format 'yyyy-ww') from one worksheet in the row of another worksheet, and then select the cell (the next step would then be to then select and copy the respective column, and then paste the values).
I have the following code:
Private Sub Button5_Click()
'Define previous week and the search range
Dim prevwk As Object
Dim SrchRng As Range
Set prevwk = ActiveWorkbook.Worksheets("Values").Range("B1")
Set SrchRng = ActiveWorkbook.Worksheets("DE").Rows(1)
'If previous week is found, select the cell
With SrchRng
Dim prevwkf As Range
Set prevwkf = SrchRng.Find(What:=prevwk)
prevwkf.Select '<----- Error is here
End Sub
I keep receiving the error message:
'Run-time error '91': Object variable or With block variable not set'.
I have tried many changes but it keeps coming down to this error message.
Many thanks for your help!

before selecting a cell you have to activate the sheet, just as you would do manually:
SrchRng.parent.Activate
prevwkf.Select
BTW you don't need that With SrchRng, and you could check for actual match found
Private Sub Button5_Click()
'Define previous week and the search range
Dim prevwk As Object
Dim SrchRng As Range
Set prevwk = ActiveWorkbook.Worksheets("Values").Range("B1")
Set SrchRng = ActiveWorkbook.Worksheets("DE").Rows(1)
'If previous week is found, select the cell
Dim prevwkf As Range
Set prevwkf = SrchRng.Find(What:=prevwk)
If Not prevwkf Is Nothing Then ' check you actually found something
SrchRng.Parent.Activate
prevwkf.Select '<----- Error is here
End If
End Sub

Related

Populating ComboBox with dynamic values from another worksheet

---Update---
Thanks for the responses, I have found that DragonSamu's updated answer works perfectly.
---Original Post---
I have been trying to figure out where I am going wrong for the past few hours but I can't spot it. I think it's because the script is trying to draw the value from the active worksheet which is not what I want. Hopefully somebody can put me on the rite track - I think the answer should be relatively obvious but I just can't see it!
Basically, I am trying to populate a Combobox with a dynamic range of values that exist in another worksheet (but in the same workbook). I can get the Combobox to populate when I run the script in the worksheet 'Materials' (which is where the dynamic list is drawn from) but not when I run it in the worksheet 'Products'.
Unfortunately the script is designed to populate Products with Materials so is be run in a UserForm when the 'Products' worksheet is open and the 'Materials' worksheet would therefore be inactive.
I should also note that this script has been adapted from code I found elsewhere on this forum, so if it seems familiar I thank you in advance :)
Private Sub UserForm_Initialize()
Dim rRange As Range
On Error GoTo ErrorHandle
'We set our range = the cell B7 in Materials
Set rRange = Worksheets("Materials").Range("B7")
'Check if the cell is empty
If Len(rRange.Formula) = 0 Then
MsgBox "The list is empty"
GoTo BeforeExit
End If
'Finds the next empty row and expands rRange
If Len(rRange.Offset(1, 0).Formula) > 0 Then
Set rRange = Range(rRange, rRange.End(xlDown))
End If
'The range's address is our rowsource
Mat1_Name_ComBox.RowSource = rRange.Address
Mat2_Name_ComBox.RowSource = rRange.Address
Mat3_Name_ComBox.RowSource = rRange.Address
Mat4_Name_ComBox.RowSource = rRange.Address
Mat5_Name_ComBox.RowSource = rRange.Address
BeforeExit:
Set rRange = Nothing
Exit Sub
ErrorHandle:
MsgBox Err.Description
Resume BeforeExit
End Sub
Any help is much appreciated.
Cheers,
Simon
From what I can see your code would be giving an error here:
If Len(rRange.Offset(1, 0).Formula) > 0 Then
Set rRange = Range(rRange, rRange.End(xlDown))
End If
Because your trying to set rRange by using Range() without defining the Worksheet first. This will get the Range from the ActiveWorksheet.
change it to the following:
If Len(rRange.Offset(1, 0).Formula) > 0 Then
Set rRange = Worksheets("Materials").Range(rRange, rRange.End(xlDown))
End If
best practice would be the following:
Private Sub UserForm_Initialize()
Dim wb as Workbook
Dim sh as Worksheet
Dim rRange As Range
On Error GoTo ErrorHandle
'Set the Workbook and Worksheet
set wb = Workbooks("products.xlsx")
set sh = wb.Worksheets("Materials")
'We set our range = the cell B7 in Materials
Set rRange = sh.Range("B7")
'Check if the cell is empty
If Len(rRange.Formula) = 0 Then
MsgBox "The list is empty"
GoTo BeforeExit
End If
'Finds the next empty row and expands rRange
If Len(rRange.Offset(1, 0).Formula) > 0 Then
Set rRange = sh.Range(rRange, rRange.End(xlDown))
End If
By properly defining and setting your Workbook and Worksheet you correctly reference to them and don't get errors.
Update:
the 2nd problem is that rRange.Address only places the Range location inside your .RowSource not the Sheet it needs to look at.
change:
Mat1_Name_ComBox.RowSource = rRange.Address
to:
dim strSheet as String
strSheet = "Materials"
Mat1_Name_ComBox.RowSource = strSheet + "!" + rRange.Address
This way it will include the Sheet name into the .RowSource

Copy value form sheet, use as worksheet names (in a loop) - VBA Excel Macro

I am attempting to Copy values in a Row, one by one from each cell, then use those values as worksheet names, one by one. One of the issues I had was skipping the first batch of sheets, so I attempted to hide the ones I don't want renamed. All other sheets should be renamed (34 of them).
I can get it all the way "ws.PasteSpecial xlPasteValues" using F8 before I get an error message that says "Run-time error '1004'L Method 'PasteSpecial' of object'_Worksheet' failed.
I have also tried using "Activesheet.PasteSpecial xlPasteValues" but it gave the same error.
Any suggestions at all are very much appreciated, this is driving me nuts. :) My back up plan is simply using the macro record and doing every rename manually, but it's not a very elegant or simple code that way, so I'd prefer not to do that.
Here is the Code:
Dim ws As Worksheet
Dim TitleID As String
Dim TID As String
Sheets("SheetName1").Activate
Set ws = ActiveSheet
Dim rng As Range, cell As Range
Set rng = ws.Range("C5", "AJ5")
For Each cell In rng
cell.Copy
Sheets("SheetName1").Visible = False
ws.Next.Select
ws.PasteSpecial xlPasteValues
Next cell
If I understand your question, properly, the below code should work.
Dim ws As Worksheet
Set ws = Sheets("SheetName1")
Dim rng As Range, cell As Range
Set rng = ws.Range("C5","AJ5")
Dim i as Integer
i = 5 'this is an arbitrary number, change to whatever number of worksheets
'you wish to exclude that are at the beginning (left most side) of your workbook
'also assumes "SheetName1" is before this number.
For Each cell In rng
Sheets(i).Name = cell.Value
i = i + 1
Next cell

Trying to loops through multiple cells in VBA

I've searched online and found a few solutions, but none of them make sense to me. I'm wondering why this specifically doesn't work:
Dim rng As Range: Set rng = Range("A5:A10")
For Each cell In rng
Dim contents As String: contents = ThisWorkbook.Sheets("ROI's").Range("cell").Value
MsgBox (contents)
Next cell
(BTW this is within a larger macro which works)
It keep saying that the error is on the third line
In addition to Scott Craners answer, take the parenthesis away from around contents in MsgBox (contents), you are not placing it into a variable so it should not be enclosed.
Sub try2()
Dim rng As Range
Dim cell As Range
Dim contents As String
Dim ws As Worksheet
Set ws = Worksheets("Sheet1")
Set rng = Range("A1:A10")
For Each cell In rng
contents = ws.Range(cell.Address(0, 0)).Value
MsgBox (contents)
Next cell
End Sub
I've been practicing wtih various problems concerning VBA...the above is just a snippet synthesizing what all the fine people above me have said about making this work. My 2 cents, brackets or not around the contents variable, the result is the same.

Clear Format of All Valued cells Dim Range VBA Issue

I just started coding a few days back and am trying to use all dim variables, since that's what everyone has been saying to use. So, I am trying to clear formats using current region (basically all cells containing value or formatting). Here is my code and I get a compile error and VBA highlights the "Entire' portion of the last code. Any thoughts? I'm new and I can't figure out what I'm doing wrong.
Sub ClearFormatting()
Dim ws as Worksheet
Dim Entire As Range
Set ws = ThisWorkbook.Sheets("Sheet1")
Set Entire = Range("A1").CurrentRegion
ws.entire.ClearFormats
End Sub
Sub ClearFormatting()
Dim ws as Worksheet
Dim Entire As Range
Set ws = ThisWorkbook.Sheets("Sheet1")
Set Entire = ws.Range("A1").CurrentRegion
Entire.ClearFormats 'no ws.
End Sub

how to create worksheets from a dynamic lis of values in vb

I have a list of values in a excel name range .I want to write a VB code so as to create worksheets using those list of values.These list of values keep on changing.
Here is the code:
Sub AddSheets()
Dim cell As Excel.Range
Dim wsWithSheetNames As Excel.Worksheet
Dim wbToAddSheetsTo As Excel.Workbook
Dim i As Integer
i = 0
Set wsWithSheetNames = ActiveSheet
Set wbToAddSheetsTo = ActiveWorkbook
For Each cell In wsWithSheetNames.Range("sheet_name").End(xlDown)
With wbToAddSheetsTo
.Sheets.Add after:=.Sheets(.Sheets.Count)
On Error Resume Next
ActiveSheet.Name = cell.Value
If Err.Number = 1004 Then
Debug.Print cell.Value & " already used as a sheet name"
End If
On Error GoTo 0
End With
Next cell
Here sheet_name(cells in a single column) is the namerange where the name of the sheets to be created is dumped.
The no of sheets may change.
My above code does not work correctly , it just creates the a sheet with the sheet name of last value in this range.Where am i going wrong? I am new to VB.what may be a better way to do this?
This line:
For Each cell In wsWithSheetNames.Range("sheet_name").End(xlDown)
Get rid of the .End(xlDown), this is only grabbing the last value, as you said.
In naming the range, just using the name already has the entire range defined.
You are almost there. Notice the line below in your script, and just get rid of .End(xldown) at the end.
---For Each cell In wsWithSheetNames.Range("sheet_name").End(xlDown)-----
change to
---For Each cell In wsWithSheetNames.Range("sheet_name")-----
Then it will add the individual sheetname one after another.