I am creating an macro-enabled Excel as a tool for generating 'create table' sql script. The sheet is created where one needs to enter the column names, data type etc., and on a button click the script will be generated. This sheet is called 'Script Generator'. Now I need an 'Index' sheet which will have table names and a button. When I click the button I need to open 'script generator' sheets for each table name and these sheets should be renamed to the table name.
The index sheet code goes like this:
Sub Add_sheets()
On Error Resume Next
Dim count As Integer
Dim r As Range
Dim sh As Worksheet
For Each r In Range("A3:A103")
If Not r = "" Then
count = 0
For Each sh In ActiveWorkbook.Sheets
If sh.Name = r.Value Then
count = count + 1
End If
Next sh
If count = 0 Then
With ActiveWorkbook.Sheets
.Add(after:=Worksheets(Worksheets.count), Type:="C:\Macro\Script_Template.xltm").Name = r.Value
End With
ActiveSheet.Hyperlinks.Add Anchor:=r, Address:="", _
SubAddress:=Sheets(r.Value).Name & "!A1"
End If
End If
Next r
End Sub
Now, the problem is I am adding the script generator saved as 'Script_Template.xltm' externally. I need only one Excel which will do this all. Means, the Index file should internally open/add the new sheets of the format 'script generator' so that it forms one complete tool. Maybe by hiding this sheet and calling its instances through macros and renaming those sheets. How to do it through VBA? Could someone help me with this?
Using True and False for setting the Visible property of a worksheet is not good practice. You should use the constants already provided - xlSheetHidden, xlSheetVeryHidden and xlSheetVisible.
xlSheetVisible will make your sheet visible and xlSheetHidden will hide your sheet. Setting it to xlSheetVeryHidden will ensure that the only way you can make the sheet visible is through VBA and not through the Excel menubar Format -> Sheet -> Unhide.
Usage:
Sheets("Script_Template").Visible = xlSheetVisible
You can create a "Script_Template" sheet and hide it and then use this code create a copy
Sheets("Script_Template").Visible = True
Sheets("Script_Template").Copy After:=Sheets(ThisWorkbook.Sheets.count)
ActiveSheet.Name = r.Value
Sheets("Script_Template").Visible = False
Related
I have the filename stated in cell B1 and I'm trying to import data from another sheet. Currently this is throwing subscription-out-of-range error. Any simple way to fix this? Or another preferred way to do this? The only requirement is to have cells containing data (text) from another workbook, not formula referring to it.
Sub UpdateFileInfo()
If (Range("B1") = "") Then
Range("A2:R200").Value = ""
Else
Filename = Range("B1").Value
Range("A2:R200") = Workbooks(Filename).GetActiveSheet.Range("A2:R200").Value
End If
End Sub
if you already know the source sheet name (e.g.: "Sheet1") you could use this
Option Explicit
Sub UpdateFileInfo2()
With Range("A2:R200") ' reference target range
If Range("B1") = "" Then ' if currently active sheet B1 cell is empty
.ClearContents ' clear referenced range content
Else
.FormulaR1C1 = "='C:\Users\...\[" & Range("B1").Value & "]Sheet1'!RC" ' fill referenced range with formulas pointing at the corresponding cell in the wanted sheet of the wanted workbook
.Value = .Value ' get rid of formulas and leave values only
End If
End With
End Sub
otherwise, you could use this pattern:
Sub UpdateFileInfo2()
With Range("A2:R200") ' reference target range
If Range("B1") = "" Then ' if currently active sheet B1 cell is empty
.ClearContents ' clear referenced range content
Else
.Value = Workbooks.Open(Range("B1").Value).ActiveSheet.Range(.Address).Value ' have refereneced range values as the newly opened workbook activesheet corresponding one
ActiveWorkbook.Close false ' close newly opened workbook
End If
End With
End Sub
while, should your Range("B1").Value not contain the full path of your file, then add it:
Sub UpdateFileInfo2()
With Range("A2:R200") ' reference target range
If Range("B1") = "" Then if currently active sheet B1 cell is empty
.ClearContents ' clear referenced range content
Else
.Value = Workbooks.Open("C:\Users\...\" & Range("B1").Value).ActiveSheet.Range(.Address).Value ' have refereneced range values as the newly opened workbook activesheet corresponding one
ActiveWorkbook.Close false ' close newly opened workbook
End If
End With
End Sub
You are getting this error because the Workbook is not open.
To do that, you'll have to include a line before the command that writes to range("A2:R200") that opens the workbook. But then, you'll have more than one workbook open, so you might want to use variables to make this cleaner like this:
Sub UpdateFileInfo()
Dim LocalWorkbook As Workbook
Dim RemoteWorkbook As Workbook
Set LocalWorkbook = ActiveWorkbook
If (Range("B1") = "") Then
Range("A2:R200").Value = ""
Else
FullFilename = Range("B1").Value
Set RemoteWorkbook = Workbooks.Open(Filename:=FullFilename, ReadOnly:=True)
LocalWorkbook.ActiveSheet.Range("A2:R200") = RemoteWorkbook.ActiveSheet.Range("A2:R200").Value
RemoteWorkbook.Close SaveChanges:=False
End If
End Sub
In general, when you get a subscription-out-of-range error, it's because you are referring to an element of a collection (in this case the workbooks collection) or an element of an array using a key or an index that does not exist.
The following is supposed to take every sheet not named "Combined Reports" and merged into the sheet Combined Reports.
My workbook has 5 worksheets in the following order:
Combined Reports
New Leave Capture
Denial Capture
Open Leave Captuer
RTW Capture
My code captures sheets 3 through 5 but it is not capturing sheet 2. Here is my code if anyone can help
Sub combine_all_Reports()
Dim J As Integer
Dim s As Worksheet
On Error Resume Next
For Each s In ActiveWorkbook.Sheets
If s.Name <> "Combined Reports" Then
Application.GoTo Sheets(s.Name).[B9]
Selection.CurrentRegion.Select
Selection.Copy Destination:=Sheets("Combined Reports"). _
Cells(Rows.Count, 1).End(xlUp)(2)
wksCombinedReports.Cells.EntireColumn.AutoFit
End If
Next
End Sub
You should avoid using Application.GoTo, Selection, and Select and instead use fully qualified objects.
Your For loop code, could be much shorter (and faster), see the code below:
For Each s In ActiveWorkbook.Sheets
If s.Name <> "Combined Reports" Then
' copy >> paste in 1 line
s.Range("B9").CurrentRegion.Copy Destination:=wksCombinedReports.Cells(wksCombinedReports.Rows.Count, 1).End(xlUp)(2)
wksCombinedReports.Cells.EntireColumn.AutoFit
End If
Next
since you already know the sheets name in advance you could code like follows:
Option Explicit
Sub combine_all_Reports()
Dim s As Worksheet
With Worksheets("Combined Reports") ' reference "Combined Reports" sheet
For Each s In Worksheets(Array("New Leave Capture", "Denial Capture", "Open Leave Captuer", "RTW Capture")) ' loop through specific sheets
s.Range("B9").CurrentRegion.copy Destination:=.Cells(.Rows.Count, 1).End(xlUp)(2) ' copy current sheet range B9 current region and paste to referenced sheet (i.e. "Combined Reports")
Next
.UsedRange.EntireColumn.AutoFit ' autofit only once all copy&paste have been made
End With
End Sub
So I have a worksheet that generates a chart type of thing using information on 2 other worksheets. On It I have an extract button which should copy the entire workbook into a new workbook whilst making the sheets where the data is pulled from invisible to the user. My issue is, the chart worksheet has other features which require macros to be run, for example buttons that hide some of it etc. The issue is I cannot find whether its actually possible to copy through macros from a workbook into the new copied workbook? Anyone have an answer to this and if so, how would you do this? Here is the code I currently have which copies the workbook into a new workbook:
Sub EWbtn()
Dim OriginalWB As Workbook, NewCRCWB As Workbook
Set OriginalWB = ThisWorkbook
Set NewCRCWB = Workbooks.Add
OriginalWB.Sheets("Generator").Copy Before:=NewCRCWB.Sheets("Sheet1")
OriginalWB.Sheets("Module Part Number Tracker").Copy Before:=NewCRCWB.Sheets("Generator")
OriginalWB.Sheets("CRC").Copy Before:=NewCRCWB.Sheets("Module Part Number Tracker")
Application.DisplayAlerts = False
NewCRCWB.Worksheets("Generator").Visible = False
NewCRCWB.Worksheets("Module Part Number Tracker").Visible = False
NewCRCWB.Worksheets("Sheet1").Delete
Application.DisplayAlerts = True
End Sub
I'd take a copy of the original file and delete/hide sheets from that.
All code is copied over as part of the save.
Sub Test()
Dim wrkBk As Workbook
Dim sCopyFileName As String
Dim wrkSht As Worksheet
sCopyFileName = "C:\MyFolderPaths\Book2.xlsm"
'Create copy of original file and open it.
ThisWorkbook.SaveCopyAs (sCopyFileName)
Set wrkBk = Workbooks.Open(sCopyFileName)
'wrkbk.Worksheets does not include Chart sheets.
'wrkbk.Sheets would take into account all the types of sheet available.
For Each wrkSht In wrkBk.Worksheets
Select Case wrkSht.Name
Case "Generator", "Module Part Number Tracker"
wrkSht.Visible = xlSheetVeryHidden
Case "CRC"
'Do nothing, this sheet is left visible.
Case Else
Application.DisplayAlerts = False
wrkSht.Delete
Application.DisplayAlerts = True
End Select
Next wrkSht
wrkBk.Close SaveChanges:=True
End Sub
I managed to find an answer to my question.. This code works fine however you need to add "Microsoft Visual Basic for Applications Extensibility 5.x" as a reference via Tools -> References. Here is the code:
Dim src As CodeModule, dest As CodeModule
Set src = ThisWorkbook.VBProject.VBComponents("Sheet1").CodeModule
Set dest = Workbooks("Book3").VBProject.VBComponents("ThisWorkbook") _
.CodeModule
dest.DeleteLines 1, dest.CountOfLines
dest.AddFromString src.Lines(1, src.CountOfLines)
Credit: Copy VBA code from a Sheet in one workbook to another?
So prior to asking this I searched and found something that was similar to what I was looking to do here.
Basically I have workbook AlphaMaster. This workbook is a template that I want to use to create new workbooks from weekly.
In this workbook there are sheets named: Monday-Saturday and additional sheets with a corresponding date for Mon, Tues, ect.
I have created a Form that loads on open of the workbook. What I want is when I click form run it will:
Run Code saving template as new workbook
Rename workbook based of input from userform1
Rename the workbooks with proper weekday
Workbook is named for a week end date dates of 6 sheets would renamed after this(example week ending 5th of Jan.) is put into user form as:
WeekEnd: Jan-5-2014
Dates
Mon:Dec.30
Tues:Dec.31
Weds:Jan.1
Thurs:Jan.2
Fri:Jan.3
Sat:Jan.4
Than click command. so far this is what I have:
Private Sub CommandButton1_Click()
Dim thisWb As Workbook, wbTemp As Workbook
Dim ws As Worksheet
On Error GoTo dummkopf
Application.DisplayAlerts = False
Set thisWb = ThisWorkbook
Set wbTemp = Workbooks.Add
On Error Resume Next
For Each ws In wbTemp.Worksheets
ws.Delete
Next
On Error GoTo 0
For Each ws In thisWb.Sheets
ws.Copy After:=wbTemp.Sheets(1)
Next
wbTemp.Sheets(1).Delete
wbTemp.SaveAs "blahblahblah\New.xlsx"
new.xlsx i want to be filled in from form
Vorfahren:
Application.DisplayAlerts = True
Exit Sub
Whoa:
MsgBox Err.Description
Resume Vorfahren
End Sub
Complications:
Currently while this does work I cant change the name of the document its named what I name it in the .saveAs area. I'm thinking I need to create an alternate function to handle this. Second, when it finishes my sheets are displayed in the reverse order of the template.
Some guidance/suggestions on where to go from here would be greatly appreciated!
A few issues here:
You cannot delete all Worksheets in a Workbook.
You should copy the sheet to the end to retain order (if the worksheets in source workbook is sorted):
For Each ws In thisWb.Sheets
ws.Copy After:=wbTemp.Sheets(wbTemp.Sheets.Count)
wbTemp.Sheets(wbTemp.Sheets.Count).Name = "NewSheetName" ' <-- Rename the copied sheet here
Next
If your source Worksheets does not have names "Sheet#" then delete the default sheets afterwards.
Application.DisplayAlerts = False
For Each ws In wbTemp.Sheets
If Instr(1, ws.Name, "Sheet", vbTextCompare) > 0 Then ws.Delete
Next
Application.DisplayAlerts = True
For SaveAs, refer to Workbook.SaveAs Method (Excel).
I use this in my application and works good
Set bFso = CreateObject("Scripting.FileSystemObject")
bFso.CopyFile ThisWorkbook.FullName, destinationFile, True
Once it's copied you can then open it in new Excel Object and do what ever you want with it.
In this latest project the desire is to have a button & macro that will do the following:
When clicked the macro will copy all the data from the existing workbook & save it to another location. To create the copy of the workbook I will be using the following code below:
Application.DisplayAlerts = False
ActiveWorkbook.SaveAs Filename:="C:\Data.xlsm"
Application.DisplayAlerts = True
This code was sourced from - http://goo.gl/t7qOyB
Once the copy has been archived, the data in the existing workbook must then be removed leaving all the formatting behind. How can removing the data but keeping the formatting be achieved?
Use the .ClearContents() property of Cells Collection
Sub ClearAll()
Dim ws As Worksheet
For Each ws In Worksheets
ws.Cells.ClearContents
Next
End Sub
This code iterates through all sheets in the current workbook and deletes the values from cells keeping the formatting.
Update!
If you wanted to clear only specific range on each sheet then
Sub ClearAll()
Dim ws As Worksheet
For Each ws In Worksheets
ws.Range("A1:B20").ClearContents
Next
End Sub
This will clear only range A1:B20 on each sheet.