VBA IFERROR to VLOOKUP referencing another sheet - vba

I am trying to insert this excel formula into a VBA code:
=IFERROR(VLOOKUP(E2,'Manual Flags'!$F$2:$L$902,7,0),"")
Essentially, my main worksheet named "ContractOrganization" needs to also pull/reference data using vlookup from another worksheet named "Manual Flags" and cells (F2 to L902) and print the result into cell L2
I tried adding a vba code below and I set my worksheets and variables ahead of time to try and clean the code, but nothing is working.
How can I reference another worksheet within a formula in vba using iferror and vlookup?
Sub AddFormula_ManualFlag()
Dim rng As Range
Dim ws1, ws2 As Worksheet
Dim result As String
Set ws1 = ThisWorkbook.Sheets("Manual Flags")
Set ws2 = ThisWorkbook.Sheets("ContractOrganization")
Set rng = ws2.Range("L2")
On Error Resume Next 'add this because if value is not found, vlookup fails, you get 1004
result = "=IFERROR(VLOOKUP(ws2.Range("E2"),ws1.Range("$F$2:$L$902").Value,7,0),"""")"
rng.Formula = result
End Sub

first remove the On Error Resume Next, it is not needed when you are putting the formula in the cell itself, only when using Application.WorksheetFunction.Vlookup.
Any vba needs to be removed from the quotes and concatenated with &:
result = "=IFERROR(VLOOKUP(" & ws2.Range("E2").Address(0,0) & "," & ws1.Range("$F$2:$L$902").Address(1,1,,1) & ",7,0),"""")"

Related

Excel VBA - Subscript out of range - Sheets name as a variable

I am trying to work on a Worksheet whose name is a variable.
I have a main sheet, called "data" where I go to catch a list of names of existing sheets.
My code is as follows :
Dim data as Worksheet
dim sheet_name as String
Dim i as Integer
Set data = ThisWorkbook.Sheets("Data")
For i = 2 to 10
sheet_name = data.Range("A"&i).Value
With ThisWorkbook.Sheets(sheet_name)
'Operations on the worksheet
End With
Next i
The error prompted is "Runtime Error 9 : Subscript Out of Range" for the specific line :
With This Workbook.Sheets(sheet_name)
It is as if the object Sheets didn't understand the string sheet_name.
The Sheet "sheet_name" exists for sure, I double-checked.
Unfortunately, I cannot call the sheet by its name because I have too many sheets to operate on, this is why I wanted to do a loop.
I tried not working with the "With" clause but just referring to every object of the sheets with "ThisWorkbook.Sheets(sheet_name) in front but doesn't work either.
Do you know if it is possible to call a string variable inside a Sheets()?
Thanks a lot for your help !
Kind regards,
The reason for your error was given in the comments above by #chris neilsen
You could use the code below to check or avoid having these kind of errors:
Option Explicit
Sub CheckShtExists()
Dim data As Worksheet
Dim sheet_name As String
Set data = ThisWorkbook.Sheets("Data")
Dim ws As Worksheet
Dim ShtNamesArr() As String
Dim i As Long
ReDim ShtNamesArr(0 To ThisWorkbook.Worksheets.Count - 1) ' resize array to number of worksheets in This Workbook
' loop thourgh all worksheets and store their names in array
For Each ws In ThisWorkbook.Worksheets
ShtNamesArr(i) = ws.Name
i = i + 1
Next ws
For i = 2 To 10
If data.Range("A" & i).Value <> "" Then ' ignore blank cells
sheet_name = data.Range("A" & i).Value
If Not IsError(Application.Match(sheet_name, ShtNamesArr, 0)) Then ' use Application.Match to see there is a sheet with this name
With ThisWorkbook.Sheets(sheet_name)
'Operations on the worksheet
End With
Else ' No Match
MsgBox sheet_name & " doesn't exists in your workbook"
End If
End If
Next i
End Sub

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

Excel: Lookup table name excel for a given variable

I have one Workbook with multiple projects. Each project has it's own sheet. In each of these sheets there are columns for order numbers ("OrderNub").
In another sheet called "MasterList" contains all of the order numbers across all project. This list is in column A.
I need a function or Macro that will search all of my sheets (bar MasterList) and will display the sheet name in column B.
Below is what I have in Excel:
Option Explicit
Function FindMyOrderNumber(strOrder As String) As String
Dim ws As Worksheet
Dim rng As Range
For Each ws In Worksheets
If ws.CodeName <> "MasterList" Then
Set rng = Nothing
On Error Resume Next
FindMyOrderNumber = ws.Name
On Error GoTo 0
If Not rng Is Nothing Then
FindMyOrderNumber = ws.Range("A1").Value
Exit For
End If
End If
Next
Set rng = Nothing
Set ws = Nothing
End Function
Option Explicit
Function FindMyOrderNumber(strOrder As String) As String
Dim ws As Worksheet
Dim rng As Range
For Each ws In Worksheets
If ws.CodeName <> "MasterList" Then
Set rng = Nothing
On Error Resume Next
Set rng = ws.Columns(1).Find(strOrder)
On Error GoTo 0
If Not rng Is Nothing Then
FindMyOrderNumber = ws.Name
Exit For
End If
End If
Next
Set rng = Nothing
Set ws = Nothing
End Function
Assumptions:
Your project sheets us Table objects. If they don't, you need to edit line 11 to point to whatever range contains the OrderNub data.
If not tables, then your projects at least use the exact same layout. In that case, you could change line 11 to something like: Set rng = ws.Range("C1").EntireColumn.Find(strOrder)
The code name of the master list is MasterList. This is not the same as the worksheet name as seen on the tab. This is the VBA code name. I prefer to use that as it is less likely to be changed and break the check. You can find the codename in the VBA editor. For instance, in this screenshot, the codename for the first worksheet is shtAgingTable and the name - as shown on the tab in Excel - is AgingTable.
This is a function, not a subroutine. That means you don't run it once. It's meant to be used like any other built-in function like SUM, IF, whatever. For instance, you can use the following formula in cell B2:
=FindMyOrderNumber($A2)

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.

Copy Multiple Ranges from userform to worksheet in another workbook

I am having a hard time with an issue I have with an excel workbook im trying to create that will parse multiple ranges defined in a userform from another workbook. My issue is that when i am attempting to paste the range in the form, the code will only paste the string and not the code itself.
Note: this is a mod attempt of Jan Karel Pieterse's range userform workaround
code below:
Private Sub cmbOK_Click() 'VALIDATION OF RANGE
Dim wbk As Workbook
Dim wst As Worksheet
Dim vbk As Variant
vbk = "[" & Me.cbxWorkbooks.Value & "]" & Me.refSelectCells.Value
If refSelectCells.Text <> "" Then
If TypeName(Selection) = "Range" Then
If IsValidRef(refSelectCells.Text) Then
OK = True
Windows("abc_123_Review_Automation.xlsm").Activate
Worksheets("CalculationSheet").Range("A2") = vbk.Value
End If
End If
End If
Me.Hide
End Sub
Example:
if vbk's value is "[Workbook]sheet1!a4:j365"
I want to paste the contents of that range address into a new workbook at "A2"
Please Help!
Range("A2") returns a range object.
If you want to modify the formula of the cell you should modify Range("A2").FormulaR1C1.
If you want to modify the value you should modifyRange("A2").Value.