Excel Vba - Calling a sheet with a variable sheet name - vba

I've been coding in VBA for some time, but this one has really stumped me.
I'm creating a workbook which creates technical certificates for machines. We have varying templates depending on the machine type and I am attempting to get my code to select the correct sheet from a user input and then populate the sheet. FYI these template sheets will be hidden and the user can only interact with the userforms.
Heres the code that is failing:
Machine = MachineType.Text '<-- input from userform, for example Machine = "Vertex 251"
Set wsCopy = ThisWorkbook.Sheets(Machine) '<--- select that machine's sheet
wsCopy.Copy '<--Run time Error 1004: Method copy of object_worksheet failed
I've tried numerous different types including just sheets(machine).copy or
Sheets(machine).activate
Activesheet.copy
but nothing has worked so far - I cannot tell if I am doing something fundamentally wrong.
Any help would be be appreciated.
Cheers.

You must unhide the sheet before copying it (at least to a new workbook as lturner notes) - you can then re-hide it
Dim shtTemplate as Worksheet, sheetWasHidden As Boolean
Set shtTemplate = ThisWorkbook.Sheets(Machine)
'handle the case where the sheet to be copied is Hidden
If shtTemplate.Visible = xlSheetHidden Then
shtTemplate.Visible = xlSheetVisible
sheetWasHidden = True
End If
shtTemplate.Copy
If sheetWasHidden Then shtTemplate.Visible = xlSheetHidden 're-hide if needed

When you have the worksheet object and use the Copy method, Excel seems to be making assumptions (or not) about where you want to put the new sheet. I pretty much always use the After option to define where the new sheet should go.
Option Explicit
Sub test()
Dim wsCopy As Worksheet
Set wsCopy = ActiveSheet
wsCopy.Copy After:=wsCopy
End Sub

Related

ms-Excel Worksheet transfer between worksbooks and vlookup

I have a simple problem(at least seems to be) that I just cannot seem to be able to find a good solution to:
I have 4 workbooks, that all contain two of the exact worksheets(rest of the worksheets are unique for each workbook). I am storing these two worksheets in a seperate workbook(so 5th workbook). Out of these 2 worksheets, 1 of them is a Data sheet made up of many tables, which I do updates on and the other one is a sheet called V, which just uses some vlookup functions to bring up the related data from this Data sheet.
I am trying to find a way to be able to pass along this data sheet to each individual workbook, instead of editing the data sheet individually for each workbook(All 4 of them).
I was able to come up with the following macro, which checks if the sheet already exists and if it does it deletes it. Then it opens up location of the excel file, copies this worksheet to the workbook and therefore I have the most "updated" version of this data worksheet.
Sub UpdateT()
Sheets("data").Visible = True
Dim wb As Workbook
Dim aw As Workbook
''Open 2nd Workbook
Set aw = Application.ActiveWorkbook
'Check if data worksheet exists, and if it does delete it
If Not GetWorksheet("data") Is Nothing Then
Application.DisplayAlerts = False
Worksheets("data").Delete
Application.DisplayAlerts = True
End If
'Check if T worksheet exists, and if it does, delete it
If Not GetWorksheet("T") Is Nothing Then
Application.DisplayAlerts = False
Worksheets("T").Delete
Application.DisplayAlerts = True
End If
Set wb = Workbooks.Open(Filename:="C:\Users\yilmadu001\Desktop\Update.xlsx")
'Copy To Different Workbook
wb.Sheets("data").Copy _
After:=aw.Sheets("Data1")
wb.Sheets("5120 TI").Copy _
After:=aw.Sheets("MENU5120")
'Close 2nd Workbook
aw.Save
wb.Close
'Hide the data worksheet
aw.Sheets("data").Visible = False
End Sub
'Function to check if worksheets exist
Function GetWorksheet(shtName As String) As Worksheet
On Error Resume Next
Set GetWorksheet = Worksheets(shtName)
End Function
The problem is the following:
When the new Data worksheet is transferred, the V worksheet is no longer working with the Vlookup function to be able to point to the relative information. So then I thought, okay what if I transfer BOTH Data and V worksheets, however that also did not work.
Is there a way to be able to use Vlookup, while copying the Data sheet? (The name is exactly the same I do not understand why it does not seem to be able to point to the cells of the table). It just looks blank, can't point to anything.
NOTE: I am not changing the format of the Data tables, basically just the values, so the format is the exactly the same.
It is probably important to note that the main excel workbooks(the 4) are in use 24/7, therefore I cannot go the other way(Update from Data workbook to the main workbook). I must "pull" the updated worksheet rather than "push".
If anyone has any suggestions I'd really appreciate. Thank you.

Excel hangs when runs VBA in Module

Excel rookie here. I'm trying a very simple task: copying and pasting cells. The Excel will go into "non responding" once the VBA runs. The code was running at one point, but as I developed more lines, Excel stopped responding. I comment out the rest of the line and only run the lines shown below, Excel still hangs. Any ideas? Thanks!
Also, I'm writing the codes in the module in Excel.
Sub EDRII()
Application.ScreenUpdating = False
Dim EDR As Worksheet, Lookup As Worksheet, FA As Worksheet
Set EDR = Sheets("for edr II")
Set Lookup = Sheets("Lookup")
Set FA = Sheets("FA_Segment_Region")
Sheets(EDR).Activate
Range("B6:X10").Copy Range("B5:X9")
Application.ScreenUpdating = True
End Sub
Excel xlsm
You have defined EDR to be a Worksheet and assigned it to be a reference to the sheet called "for edr II".
When you try to use it later, in the line saying
Sheets(EDR).Activate
you are using EDR in a spot where VBA is expecting a String or an Integer (or Long).
That line should simply say
EDR.Activate
It's also a good idea to avoid Activate and Select whenever possible so, rather than activating the sheet, you could just use
EDR.Range("B6:X10").Copy EDR.Range("B5:X9")
for the Copy statement.
Here's some pointers:
Indent your code so it's easier to follow (minor point in your example)
Fully qualify your references (ThisWorkbook.Worksheets(), EDR.Range(), etc)
Rather than copying and pasting, use .Value
Your code was breaking down because you were trying to activate EDR with Sheets(EDR).Activate which should just be EDR.Activate. Either way, when you take into account the points above you see that you don't need to Activate anything anyway!
Sub EDRII()
Application.ScreenUpdating = False
Dim EDR As Worksheet, Lookup As Worksheet, FA As Worksheet
Set EDR = ThisWorkbook.Worksheets("for edr II")
Set Lookup = ThisWorkbook.Sheets("Lookup")
Set FA = ThisWorkbook.Sheets("FA_Segment_Region")
EDR.Range("B5:X9").Value = EDR.Range("B6:X10").Value
Application.ScreenUpdating = True
End Sub

Copy a range from excel to another workbook in a new worksheet

I'm very new to VBA macros and have taught myself some code but I'm struggling with my current piece of work and can't find the answer I am looking for.
I want to copy a range of cells (B3:N21) from one workbook to another "master" workbook - which seems simple enough - but I would like it to copy into a blank/new worksheet in the Master copy every time the Macro is run.
The range contains formulas, I would only need the values copied to the Master workbook.
Any help with this would be greatly appreciated.
Thanks
Worksheets("Sheet1").Range("C1:C5").Copy
Worksheets("Sheet2").activate
Worksheets("Sheet2").Range("D1:D5").PasteSpecial _
Operation:=xlPasteSpecialOperationAdd
End With
I think you only need paste special, this is an example
try this
Option Explicit
Sub main()
Dim masterWb As Workbook
Dim mySht As Worksheet
Set mySht = ThisWorkbook.ActiveSheet '<~~ assuming you're copying values from active worksheet of the workbook the macro resides in
' beware: if you start the macro while the active sheet is not the one you want, this will lead to unespected results
Set masterWb = Workbooks("Master") '<~~ Change "Master" with whatever name your master workbook must have
' beware: we're assuming "Master" workbook is already open, otherwise this line will throw an error
With masterWb.Worksheets.Add
.Range("B3:N21").Value = mySht.Range("B3:N21").Value
End With
End Sub
mind the comments
the code above can be reduce to a much less verbose (and self explanatory, too) one like follows
Sub main2()
Workbooks("Master").Worksheets.Add.Range("B3:N21").Value = ThisWorkbook.ActiveSheet.Range("B3:N21").Value
End Sub
where apply the same comments of the lengthy code, which is:
assuming you're copying values from active worksheet of the workbook the macro resides in
beware: if you start the macro while the active sheet is not the one you want, this will lead to unespected results
change "Master" with whatever name your master workbook must have
beware: we're assuming "Master" workbook is already open, otherwise an error would be thrown

Excel VBA copy Run-Time error '1004'

I can't figure out what's wrong with my VBA:
Private Sub CommandButton4_Click()
Sheets("Opgave").Select
Range("F9:G14").Select
Selection.Copy
Sheets("Reserve").Select
Range("E3").Select
End Sub
Excel says Range("F9:G14").Select is wrong!
You need to Activate the sheet, because Range is implicitly referring to the active worksheet, and you're wrongly assuming Selecting something will necessarily Activate it.
I've executed your code with "Sheet1" and "Sheet2" without any error being thrown, "Sheet1!F9:G14" selected for copy and "Sheet2!E3" selected, which seems to be what this code wants to achieve.
Still, I'd like to say...
Avoid problems, avoid Select and Activate in VBA code.
Sheets have a CodeName property that you can change from, say, Sheet1 to OpgaveSheet, or Sheet2 to ReserveSheet. Then this code is valid:
OpgaveSheet.Range("F9:G14").Copy ReserveSheet.Range("E3")
The Name of a worksheet is the text that's displayed in the tab for it in Excel. You can also use that to get a reference to a worksheet:
Dim opgaveSheet As Worksheet
Set opgaveSheet = ThisWorkbook.Worksheets("Opgave")
Dim reserveSheet As Worksheet
Set reserveSheet = ThisWorkbook.Worksheets("Reserve")
And when you want to work with a specific range, keep a reference to it instead of Selecting it and working with the Selection:
Dim source As Range
Set source = opgaveSheet.Range("F9:G14")
Dim destination As Range
Set destination = reserveSheet.Range("E3")
source.Copy destination
Code that doesn't constantly interact with worksheets (via Select and Activate) is going to perform better, will be easier to follow, debug and maintain, and will be much less error-prone.

How to access a closed Excel Workbook using vlookup vba

I'm trying to create a Excel VBA macro that uses VLOOKUP to access a range of cells in a closed workbook. I'm not too good at using the VBA editor, but it doesn't seem to show a lot of useful information about errors.
Sub WorkBookWithData()
Dim currentWb As Workbook
Set currentWb = ThisWorkbook
Dim currentWs As Worksheet
Set currentWs = currentWb.Sheets(1)
Dim strFormula As String
strFormula = "=VLOOKUP(currentWs.Range("B2"),'Macintosh HD:Users:myself:Documents:l[Master_Terms_Users.xlsm]Master_Terms_Users.csv'!A1:B222,2,false)"
currentWs.Range("C2").Formula = strFormula
End Sub
Excel VBA editor is hanging up on the "strFormula = "=VLOOKUP..." section.
Thanks
Reference from Siddharth Rout's comments.
The main problem in your code is this line:
strFormula = "=VLOOKUP(currentWs.Range("B2"),'Macintosh HD:Users:myself:Documents:l[Master_Terms_Users.xlsm]Master_Terms_Users.csv'!A1:B222,2,false)"
because of this code currentWs.Range("B2"). We know that you want to indicate Range("B2") of Current Sheet(same sheet). So, you can use as follow:
strFormula = "=VLOOKUP(B2,'Macintosh HD:Users:myself:Documents:l[Master_Terms_Users.xlsm]Master_Terms_Users.csv'!A1:B‌​222,2,false)"
Why? It can use just B2 because you set formula to a cell which is in the same sheet. So, it is not need to indicate the Sheet Name.
And If you want to set a cell which is from other sheet, you need to indicate Sheet Name in that case. So, should use as follow:
strFormula = "=VLOOKUP(" & currentWs.name & "!B2,'Macintosh HD:Users:myself:Documents:l[Master_Terms_Users.xlsm]Master_Terms_Users.csv'!A1:B222,2,false)"
This looks nothing like what I had previously, but it works.
Sub Check_Master_Values()
Dim newCurWb As Workbook
Set newCurWb = Workbooks(2)
newCurWb.Activate
newCurWb.Sheets(1).Range("C2").Formula = "=VLOOKUP(B2,'Macintosh HD:Users:myself:Documents:[Master_Terms_Users.xlsm]Master_Terms_Users.csv'!$A$1:$B$269,2,FALSE)"
End Sub
In my first attempt, I didn't follow the chain of assignments from workbook, to sheets, to ranges. As you can see in this code, I Dim a new Workbook - then the big ah-ha moment, I needed to assign it to the correct open workbook. Then, I activated the workbook, and finally accessed the Sheets object and Range.
I also know now that my workbook selection number will vary depending on how many other workbooks are open. The ThisBook didn't work because somehow in the process, the workbook that ThisBook referenced, changed. That is probably also why my initial code didn't work, in addition to the improper coding in the VLOOKUP.
It would be good if there was a way to specify which workbook on the fly.
Thanks to everyone who gave help on the VLOOKUP part.