Using macros to create and rename a new sheet in Excel 2013 - vba

My objective is simple, when a certain field consists of text, I need a button that transfers this text into a sheet.
For example, I write "GOOGLE LTD", then I click that button, a new sheet is created and renamed too "GOOGLE LTD". Refer to picture below.
I have searched through the internet, but cannot find a simple tutorial that describes how to create and rename a sheet by using macros.

Here is a backbone you will need to change the txt variable to = your range:
Sub create()
Dim txt As String
Dim sht As Worksheet
txt = ActiveSheet.Range("D4").value
Set sht = Sheets.Add(After:=Worksheet(Sheets.Count))
sht.Name = txt
End Sub

Related

Unable to create a logic to convert the values in Excel to CSV the right way with VBA

I made the code to convert the values to the csv file but the problem is
that I'm not sure if this is the right way because this is the first time I even touched VBA macro! As seen in the image I provided, there is a button "Convert to CSV", when I tap it, the macro will call ExportWorksheetAndSaveAsCSV method and will convert the entire sheets contents into csv. However, it looks like it converts the entire sheet it'self.
What I want to do is the following steps .
1.Pass in the Sheet name as a parameter like ExportWorksheetAndSaveAsCSV("Sheet2"), so that it can be used as a file name. But I'm not sure how I can pass a parameter in function from the Buttton.
2.Convert the values in the columns E to I to CSV. If possible want to have the tites of the data show in the first row of the csv file.
I attached the image and the code so you can see. Some tips or examples will be really helpful! I would love to hear from you.
Public Sub ExportWorksheetAndSaveAsCSV()
Dim wbkExport As Workbook
Dim shtToExport As Worksheet
Dim book As String
Dim fileName As String
book = "Sheet1"
fileName = "test.csv"
Set shtToExport = ThisWorkbook.Worksheets(book) 'Export to CSV file
Set wbkExport = Application.Workbooks.Add
shtToExport.Copy Before:=wbkExport.Worksheets(wbkExport.Worksheets.Count)
Application.DisplayAlerts = False
wbkExport.SaveAs fileName:="C:\Users\myStuff\Documents\" & fileName, FileFormat:=xlCSV
Application.DisplayAlerts = True
wbkExport.Close SaveChanges:=False
End Sub

Export multiple ranges to a single PDF using VBA

I'm trying to write a macro to cycle through a dropdown menu. Everytime the value in the drop down changes it will change the values on the worksheet. I won't to capture a range of the worksheet for every value in the dropdown in a VBA array and then export all of these ranges to single PDF. I'm able to export them one at a time to multiple PDFs but this isn't the objective. The problem I seem to be having is storing the different ranges in an Array.
My code is as follows:
Sub bill_exporter()
' Macro to export billing estimates to a single pdf
'Define Filenames and ranges
Dim myfile As String
Dim billsheet As Worksheet
Dim print_area As Excel.Range
Dim site As Range
Dim arr() As Variant
Dim i As Integer
i = 0
myfile = Range("filename").Value
Set billsheet = ActiveWorkbook.Sheets("Mock Bill")
For Each site In Range("meters")
billsheet.Calculate
billsheet.Range("$R$10").Value = site
'Create Vertical Page Breaks
billsheet.VPageBreaks.Add Before:=Range("C3")
billsheet.VPageBreaks.Add Before:=Range("R3")
'Set Print Area
Set print_area = billsheet.Range("C3:R50")
Set arr(i) = print_area.Value
i = i + 1
Next site
Array(arr).ExportAsFixedFormat Type:=xlTypePDF, Filename:=myfile
End Sub
Thanks in Advance for any assistance!
So you can't collect them all into a single array, solution is to create multiple dummy sheets and delete them when done:

How to pass the hyperlink string from one workbook to another

I have two workbooks "UI.xlsm" and "Gas_Insulated_MV_Circuit.xlsm", in the first workbook (UI.xlsm) i ave maintained a list of hyperlinks in a particular column, on click of the link it will take me to a respective other workbooks.
The task is to capture the text of the clicked hyperlink from "UI.xlsm" workbook and i have to use the same value in "Gas_Insulated_MV_Circuit.xlsm"
Below is the code from UI.xlsm workbook where I am capturing the clicked hyperlink cell text and storing it as string
Private Sub Worksheet_FollowHyperlink(ByVal Target As Hyperlink)
Dim BR as String
BR = Target.Range.Text 'Here i'm storing the clicked cell text
End Sub
Now i need to use the BR string value in another workbook "Gas_Insulated_MV_Circuit.xlsm"
Public BR as String ' I have declared BR as a public variable
Private Sub CommandButton27_Click()
Dim WbUI as Workbook
Dim WsUI as Worksheet
Dim File1 as string
Set WbUI = Workbooks ("UI.xlsm")
Set WsUI = WbUI.Sheets("Sheet1")
File1 = BR ' I want something like this, where i can assign BR value from
UI.xlsm workbook to File 1 of the current workbook
End Sub
Could anyone kindly help me in achieving it.
I created a defined name (e.g. myBR) in the UI.xlsm workbook with =Sheet1!A1 as the Refers to:. With that defined name 'seeded', I changed your Worksheet.FollowHyperlink event macro to,
Private Sub Worksheet_FollowHyperlink(ByVal Target As Hyperlink)
ThisWorkbook.Names("myBR").RefersToR1C1 = _
Chr(61) & Chr(34) & Target.Range.Text & Chr(34)
End Sub
In the Gas_Insulated_MV_Circuit.xlsm workbook, I can retrieve the most recently clicked hyperlink's cell text (i.e. TextToDisplay property) with,
=UI.xlsm!myBR
With both workbooks open, the cell value changes were immediate. Assignment to a string or integer variable in VBA should be no problem.

Inserting a Worksheet between two specific worksheets

I have created an excel macro which allows a user to insert a new client and based off the clients name a worksheet is created. How I have this created is by using the following code: Sheets("Template").Copy After:=Sheets("Template")
Sheets("Template (2)").Visible = True
Sheets("Template (2)").Name = ClientAbbrev
So what this does is create a copy of the template sheet which is hidden and creates a new tab which is named after the client abbreviation. This new 'entry' is generally inserted between two 'book-ends' - Template and Template End. So the newly inserted tab would go here:
Template, NEW TAB HERE, Template End.
Now that I've hidden both Template and Template End, when I Insert New Clients instead of having it appear like above, it appears like this:
Template, Template End, NEW TAB HERE.
This is a problem as I have a summing array which takes all the data between the Start and End Tabs and now it doesn't seem to work unless the Book-End Tab isn't hidden. Can anyone shed some light on this or tell me how to write a macro to insert tabs specifically between those two tabs?
Thanks!
Try this:
Option Explicit
Public Sub addNewSheet()
Dim t As Worksheet, ws As Worksheet
Set t = ThisWorkbook.Worksheets("Template")
t.Copy After:=t
Set ws = ThisWorkbook.Worksheets(t.Index + 1)
With ws
.Visible = True
.Name = "New client"
End With
End Sub

How to add a new spreadsheet with VBA-Code, using VBA

I am creating a macro and part of the macros function is to make VBA create a new spreadsheet. Because of the nature of distribution the name will change. I need to add code to this spreadsheet. Is there anyway I can do this?
Jook has already explained how it works. I will take it a step further.
The syntax of adding a worksheet is
expression.Add(Before, After, Count, Type)
If you check inbuilt Excel's help then you can see what Before, After, Count, Type stands for
FROM EXCEL"S HELP
Parameters (All 4 parameters are Optional)
Before - An object that specifies the sheet before which the new sheet is added.
After - An object that specifies the sheet after which the new sheet is added.
Count - The number of sheets to be added. The default value is one.
Type - Specifies the sheet type. Can be one of the following XlSheetType constants: xlWorksheet, xlChart, xlExcel4MacroSheet, or xlExcel4IntlMacroSheet. If you are inserting a sheet based on an existing template, specify the path to the template. The default value is xlWorksheet.
Once the sheet is created then you need to use .insertlines to create the relevant procedure and to also embed the code that you want to run.
NOTE - IMP: If you want the code to embed code in the VBA project, you need to ensure that you have "Trust Access to the VBA Project Object Model" selected. See snapshot.
Here is an example where I am creating a sheet and then embedding a Worksheet_SelectionChange Code which will display a message "Hello World"
CODE - TRIED AND TESTED
Option Explicit
Sub Sample()
Dim ws As Worksheet
Dim nLines As Long
Dim VBP As Object, VBC As Object, CM As Object
Dim strProcName As String
Set ws = Worksheets.Add
Set VBP = ThisWorkbook.VBProject
Set VBC = VBP.VBComponents(ws.Name)
Set CM = VBC.CodeModule
strProcName = "Worksheet_SelectionChange"
With ThisWorkbook.VBProject.VBComponents( _
ThisWorkbook.Worksheets(ws.Name).CodeName).CodeModule
.InsertLines Line:=.CreateEventProc("SelectionChange", "Worksheet") + 1, _
String:=vbCrLf & _
" Msgbox ""Hello World!"""
End With
End Sub
This is how the new sheet code area looks once you run the above code.
the following code will add you a spreadsheet.
Public Sub Workbook_Add()
Dim wks As Worksheet
Set wks = ThisWorkbook.Worksheets.Add(, , 1, xlWorksheet)
With wks
'set codename of wks
ThisWorkbook.VBProject.VBComponents(.CodeName).Name = "tblWhatever"
'set tablename of wks
.Name = "whatever"
'add code (untested demo)
'ThisWorkbook.VBProject.VBComponents(.CodeName).CodeModule.InsertLines 1, "Option Explicit"
'add code (as of example from excel-help)
'Application.VBE.CodePanes(1).CodeModule.InsertLines 1, "Option Explicit"
End With
End Sub
If you need to add VBA-Code to this specific spreadsheet, you should further inspect the VBProject object - look for CodeModule and then i.e. InsertLines.
A further hint for you - I would try to use the CodeNames of your tables. It is less likely to be changed - BUT it might be not that comfortable to use in your code at first. I had to get used to it, but for me it has many advantages against using a tables name.
Hope this helps ;)
The default .Add method adds a sheet at the start of the list. Often you want to add it at the end before adding the code lines, as explained by Siddarth Rout. To do that anywhere you can use:
ActiveWorkbook.Worksheets.ADD After:=ActiveWorkbook.Sheets(ActiveWorkbook.Worksheets.Count)
It is easier to read if you have defined and set WB:
Dim WB as Excel.workbook
Set WB = ActiveWorkbook
WB.Sheets.ADD After:=WB.Sheets(WB.Sheets.Count)
Set VBC = ActiveSheet 'If using in Siddarth Rout's code above
Sheets and Worksheets are interchangeable, as illustrated.