Using VBA: double clicking cell creates new sheet, cell is also hyperlinked to new sheet - vba

Alright, so I am brand new at this. New role at work. I received this excel request:
Double clicking any cell in a sheet creates a new sheet.
Original cell that is double clicked now turns into a hyperlink, linking to the newly created sheet.
The double click function for this cell that was originally double click is removed.
I'm honestly stuck. I've not really programmed using VBA before. I've figured out how to create a new sheet upon double click, and I've figured out how to hyperlink. But I can't figure out how to hyperlink to a newly created sheet, and to remove the double click function from that original cell!
Here's all I have...
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
Sheets.Add
End Sub
Also, forgive me if I'm breaking any rules here, this is my first time posting here. Thank you very much for your help!

You're on the right pathway, just need a few more components. A key point is to declare and use object variables (ws in this case)
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
Dim ws As Worksheet
' Prevent screen flicker
Application.ScreenUpdating = False
' Add worksheet
Set ws = Me.Parent.Worksheets.Add
' Add Hyperlink
Target.Hyperlinks.Add Anchor:=Target, Address:="", SubAddress:=ws.Cells(1, 1).Address(True, True, , True), TextToDisplay:=ws.Name & "!A1"
' Restore original sheet as active
Me.Activate
' Disable original Doubleclick action
Cancel = True
' Restore screen updating
Application.ScreenUpdating = True
End Sub

Related

VBA - Run-time error '1004'

A bit of context, this is my first time programming using VBA in excel,
and I'm trying to create a form that fills out a spreadsheet.
I'm currently getting the error message: "Run-time error '1004': Method 'Worksheets'of object '_Global' failed
I've searched online and have tried various solutions, but I think basically it comes down to a lack of understanding on my part.
Private Sub CommandButton1_Click()
'When pressing save, save values in spreedsheet locations
ActiveSheet.range("c8").Value = ContactName.Value
ActiveSheet.range("b19").Value = ModelNumber.Value
ActiveSheet.range("d19").Value = SerialNumber.Value
ActiveSheet.range("g19").Value = IncidentNumber.Value
ActiveSheet.range("j19").Value = Description.Value
ActiveSheet.range("c7").Value = PortLocation.Value
'save file
ActiveWorkbook.SaveAs Filename:= _
"D:\Users\611281\Downloads\Zebra\EmailMeToZebra.xlsx", FileFormat:=xlOpenXMLWorkbook, ReadOnlyRecommended:=False, CreateBackup:=False
End 'after pressing save, close down sheet.
End Sub
Private Sub UserForm_Initialize()
Me.PortLocation.List = Worksheets("Data lookup_ports").range("e3:e200").Value
Dim MyTempWkBk As Workbook
Dim MyCurrentWin As Window
Set MyCurrentWin = ActiveWindow
Set MyTempWkBk = Workbooks.Open("D:\Users\611281\Downloads\Zebra\GUI.xlsm")
MyCurrentWin.Activate 'Allows only a VERY brief flash of the opened workbook
MyTempWkBk.Windows.Visible = False 'Only necessary if you also need to prevent
'the user from manually accessing the opened
'workbook before it is closed.
'Operate on the new workbook, which is not visible to the user, then close it...
End Sub
Private Sub UserForm_Terminate()
End 'when pressing x, close down window, do not save.
End Sub
I'm getting the error on the code:
Me.PortLocation.List = Worksheets("Data lookup_ports").range("e3:e200").Value
Which is just me trying to populate a ListBox from a spreadsheet range
Have you tried naming the workbook? This is assuming the line with the error is referring to a cell range in thisworkbook. Also, make sure to check the name of the sheet you are referring to for exact spelling (if spelling appears correct, also check for lagging spaces.) Also, is the worksheet hidden? If so, this may need to be added before calling the sheet.
wb.sheets("Data lookup_ports").Visible = True
Can try the below edit in the meantime.
Private Sub UserForm_Initialize()
Dim MyTempWkBk As Workbook
Dim MyCurrentWin As Window
Dim WB as Workbook
Set WB = ThisWorkBook
wb.sheets("Data lookup_ports").Visible = True
Me.PortLocation.List = WB.Sheets("Data lookup_ports").Range("E3:E200").Value
Set MyCurrentWin = ActiveWindow
Set MyTempWkBk = Workbooks.Open("D:\Users\611281\Downloads\Zebra\GUI.xlsm")
MyCurrentWin.Activate
MyTempWkBk.Windows.Visible = False 'Only necessary if you also need to prevent
'the user from manually accessing the opened
'workbook before it is closed.
'Operate on the new workbook, which is not visible to the user, then close it...
End Sub
Private Sub UserForm_Terminate()
End 'when pressing x, close down window, do not save.
End Sub

Disable alert when manually deleting a sheet

Is there a way in VBA to disable the alert that pops up when MANUALLY deleting a sheet (right click sheet and delete)? I have seen Application.DisplayAlerts = False, however this seems to only work for me when deleting a sheet using VBA (Sheets("Sheet1").delete). I am trying to disable the alert for the whole workbook when you manually right click on a sheet and click delete. Thanks.
In case anyone else is looking for the same scenario:
...eliminate the need to confirm deleting a sheet when presenting the
workbook in meetings. While going through the sheets I often double
click on pivot tables to view detail, and I would like to eliminate
the pop-up alert when I delete the generated sheet...
If new sheets are generated only when double-clicking a pivot table, this might be a suitable solution
Placed in ThisWorkbook, the code bellow will delete any new sheets, when selecting a different sheet
Option Explicit
'Place this code in ThisWorkbook module
'Expects that all new sheets are generated by double-clicking a pivot table
Private pivotWs As Worksheet
Private Sub Workbook_NewSheet(ByVal Sh As Object)
Set pivotWs = Sh
End Sub
Private Sub Workbook_SheetDeactivate(ByVal Sh As Object)
If Not pivotWs Is Nothing Then
If Sh.Name = pivotWs.Name Then
Application.DisplayAlerts = False
pivotWs.Delete
Set pivotWs = Nothing
Application.DisplayAlerts = True
End If
End If
End Sub

Sub that displays a line chart for a 2 entries table when a button is clicked

I am currently trying to create a sub (Excel VBA) that generates a form that displays a line chart for months and letters I want to freely select in a 2 entries table.
I want my sub to start when I click on a button that I already created (called Display Chart or Button1_Click).
Here is the code I came out with :
Sub Button1_Click()
GenerateChart.Show
End Sub
Sub GenerateChart()
On Error Resume Next
Dim MyChart As Chart
Dim DataRange As Range
If ActiveSheet.Name = "Sheet3" And Selection.Cells.Count > 0 Then
Set DataRange = Selection
Set MyChart = ActiveSheet.Shapes.AddChart.Chart
MyChart.SetSourceData Source:=DataRange
MyChart.ChartType = xlBarStacked
End If
End Sub
For some reason, this does not seem to work. I think I did something wrong regarding the button click part. Indeed, I do not understand how this event is called (Display Chart or Button1_Click) and how to code it. Therefore I cannot check if my other lines of codes are correct.
I hope someone will be able to help me out, thanks a lot !
Assign a Macro GenerateChart with the button and Select the data for which you need to create a Chart and click the button, I think you are not selected the data while you clicking the button here you used
Set DataRange = Selection

Input Box on workbook open

I am trying to come up with some vba code to open an input box automatically as soon as the workbook is opened and have the user enter a date and then have the date placed in the A1 cell. I have written the code below but the input box is not pulling up at all it just opens the workbook and moves on.. not sure what is happening. Any and all help is appreciated.
Thanks!
Option Explicit
Private Sub workbook_open()
Dim cellvalue As Variant
Dim ws As Worksheet
Set ws = Worksheets("Workbench Report")
ReShowInputBox: cellvalue = Application.InputBox("Please Enter Todays Date (dd/mm/yyyy)")
If cellvalue = False Then Exit Sub
If IsDate(cellvalue) And CDate(cellvalue) < Date Then
ws.Range("A1").Value = DateValue(cellvalue)
Else: MsgBox ("Invalid Date!")
GoTo ReShowInputBox
End If
End Sub
Your code triggers upon the Workbook opening for me. Try these steps.
Open up Excel and Save As, changing the extension to .XSLM
Open up the VBA Editor (ALT + F11)
In the left-hand window, locate your macro file (the one you just created and named - it's in brackets after "VBA Project"), drilldown to "This Workbook" and double-click it.
Paste your code into the right-hand window
Save the file and re-open.
See attached diagram.
By the way, "cellValue = false" should probably be cellValue = "" since InputBox is returning a string and not a boolean value.
For Workbook_Open events the script needs to reside in the private module (ThisWorkbook)
From Ozgrid:
the Workbook_Open event is a procedure of the Workbook Object and as
such, the Workbook_Open procedure MUST reside in the private module of
the Workbook Object (ThisWorkbook).

Excel VBA - Capitalizing all selected cells in column on double click

I have a very simple VBA script, that capitalizes the selected cell:
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
ActiveCell.Value = UCase(ActiveCell.Value)
End Sub
It works as expected, but sometimes I would like to capitalize all cells in a selected column, but only if I double click on the column itself. It seems that I cannot receive events with Worksheet_BeforeDoubleClick when clicking the column fields..
Is there some workaround for this?
Like I mentioned, Why not a shortcut key?. You can assign a shortcut key for your macro as shown below
Now all you have to do is select the column and press the shortcut key.
Also, instead of looping through every cell in a column, here is a code which is based on a ONE LINER HACK by Peter Albert.
Put this in a module.
Sub ChangeToUpper()
Dim rng As Range
'~~> Check if what the user selected is a valid range
If TypeName(Selection) <> "Range" Then
MsgBox "Select a range first."
Exit Sub
End If
Set rng = Selection
rng = WorksheetFunction.Transpose(Split(UCase(Join( _
WorksheetFunction.Transpose(rng), vbBack)), vbBack))
End Sub
Screenshot:
If DoubleClick is not mandatory, you could use BeforeRightClick. If you want to keep original right click context menu, you could import the module and check for Ctrl/Alt/Shift
Option Explicit
Private Sub Worksheet_BeforeRightClick(ByVal Target As Range, Cancel As Boolean)
Dim condition As Boolean
condition = True ' check Ctrl/Alt/Shift using http://www.cpearson.com/excel/KeyTest.aspx
If condition Then
MsgBox "Right Click at " & Target.Address
Cancel = True
End If
End Sub
Another option is to assign a Ctrl+[] in Macro options to a macro instead of an event handling and call the macro to process the Selection object.