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

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.

Related

VBA IFERROR to VLOOKUP referencing another sheet

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),"""")"

Ignore blanks in a range

Can some one help with the last bit of this code please, I have a range maximum ("A1:A54") when i set to this range and only (A1:A10) have a cell value which is the name of a sheet in another workbook.
This code is working but returns a
runtime 9 error
I really want to add if blank ignore if I change to range I have set to A1:A10 then no error. I think it might be there is no worksheets in the other workbook this is why I get an error on this loop.
Have looked how to ignore blanks but none of the answers i have found have worked.
I really want a if cell = "" then ignore currently I thought exit sub would work
Sub Iedextraction()
Dim wkb As Excel.Workbook, wkb1 As Excel.Workbook
Dim wks As Excel.Worksheet, wks1 As Excel.Worksheet
Dim cell As Range
Dim rng As Range
Workbooks.Open Filename:= _
"D:\Projects\ASE Templates\ASE Template White Book.xlsx"
Set wkb = Excel.Workbooks("ASE RTU Addressing with Automation.xlsm")
Set wks = wkb.Worksheets("Tab Names from White book")
Set wkb1 = Excel.Workbooks("ASE Template White Book.xlsx")
Set rng = wks.Range("A1:A54")
For Each cell In rng
wkb1.Sheets(cell.Value).Copy After:=Workbooks_
("ASE RTU Addressing with Automation.xlsm").Sheets(4)
If cell = "" Then Exit Sub
Next
' On Error GoTo 0
End Sub
Add conditional instruction:
If cl <> "" Then wkb1.Sheets(cell.Value).Copy After:=Workbooks _
("ASE RTU Addressing with Automation.xlsm").Sheets(4)
And remove:
If cell = "" Then Exit Sub
Your error occurs most probably because you try to copy before you do the check. So, at the end, you try to get a sheet with no name. :)
It is better practice to use dynamic ranges since it's likely going to change at some point in the future. There are multiple ways of doing this, but my go to method is something like this:
Dim rn As Range
Set rn = Range(Range("A1"), Range("A1").End(xlDown))
So your issue would be resolved (assuming the blank cells are truly empty) and you will not have to test for blank cells.
Regardless, you should mark one of the above answers are correct if they fixed your issue.

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

excel macro to find and copy a block from one workbook to matching value in another workbook starting in the same row (using offset and resize)

I think I've almost got it what I'm trying to do is update a clients report file from my workbook for each shift.
The report is set up with a column with a date/time format (every 2 hours) for each quarter (i.e. "05/05/16 14:00" "05/05/16 16:00" ect).
I have set up my workbook with formulas to report the data in the same format.
report
So what I need it to do is
open the report file
select the data in e18 (cell I've highlighted with red box)
find the cell in the report file
copy the block data with the purple box
paste(values) to matching location based on found data
here is the code I have so far it's finding the data but pasting it in the first row instead of the matching row.
I'm new to VBA so its most likely something simple I didn't understand.
Sub ONGOING()
Dim rFndCell As Range
Dim strData As String
Dim stFnd As String
Dim fCol As Integer
Dim sh As Worksheet
Dim ws As Worksheet
Set ws = ThisWorkbook.Sheets("REPORTING")
Set sh = Workbooks.Open("F:\report.xlsm").Worksheets("Production data")
stFnd = ws.Range("E18").Value
With sh
Set rFndCell = .Range("A:IV").Find(stFnd, LookIn:=xlValues)
If Not rFndCell Is Nothing Then
fCol = rFndCell.Column
ws.Range("G18:N24").Copy
sh.Cells(6, fCol).Offset(, 2).Resize(7, 8).PasteSpecial xlPasteValues
Else 'Can't find the item
MsgBox "Not Found"
End If
End With
End Sub
Thanks
In IF condition replace
sh.Cells(6, fCol).Offset(, 2).Resize(7, 8).PasteSpecial xlPasteValues
to
sh.Cells(6, fCol).Offset(rFndCell.Row, 2).Resize(7, 8).PasteSpecial xlPasteValues