Worksheet_BeforeDoubleClick for a selection - vba

i have the below code that doesn't work for a selection:
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
Dim Rng1 As Range
Dim I As Integer
If Selection.Count > 1 Then
For Each cell In Selection
If I = 0 Then
Set Rng1 = Range(cell.Address)
Else
Set Rng1 = Union(Range(cell.Address), Rng1)
End If
I = I + 1
Next cell
MsgBox "You have selected the range " & Rng1.Address(False, False)
Rng1.End(xlDown).Offset(0, 1).Activate
Else
MsgBox "you are in " & ActiveCell.Address(False, False)
ActiveCell.Offset(1, 0).Activate
End If
End Sub
I tried selecting a range of cells and then double clicking, does anybody know if that is even possible?

Because double-clicking collapses any multi-cell selection you have previously made, you'd need to keep track of it, and then check whether Target is within it.
Something like:
Dim rng As Range
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
If Not rng Is Nothing Then
If Not Application.Intersect(Target, rng) Is Nothing Then
Debug.Print "Clicked in selected range: " & rng.Address()
Else
Debug.Print "Cell: " & Target.Address()
End If
Set rng = Nothing
Else
Debug.Print "No previous range: clicked in " & Target.Address()
End If
End Sub
'keeping track of the last multi-cell range selected....
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
If Target.Count > 1 Then Set rng = Target
End Sub

Related

IF Null exit sub code

I'm trying to check that if cells are empty or null, that it would display a message and exit sub. Here's my code:
With Worksheets(1).[D3:D4, D6:D14]
If WorksheetFunction.CountA(.Cells) = 0 Then
MsgBox "Nothing to generate" & vbNewLine & _
"Set parameters and click generate."
Exit Sub
End If
End With
But the code only works if the entire [D3:D4, D6:D14] are empty. I want it to exit sub even just one of the cells are empty. All cells needs have content for it to continue sub. Please help.
You need to seach inside the Range, try the code below:
Sub CheckEmptyCellsinRange()
Dim Rng As Range
Dim cell As Range
Set Rng = Worksheets(1).[D3:D4, D6:D14]
For Each cell In Rng
If IsEmpty(cell) Or IsNull(cell) Then
MsgBox "Nothing to generate" & vbNewLine & _
"Set parameters and click generate."
Exit Sub
End If
Next cell
End Sub
You can also use SpecialCells:
Sub Check()
Dim rng1 As Range
On Error Resume Next
With Worksheets(1).[D3:D4, D6:D14]
Set rng1 = .SpecialCells(xlBlanks)
If Not rng1 Is Nothing Then
MsgBox "Nothing to generate" & vbNewLine & _
"Set parameters and click generate."
Exit Sub
End If
End With
End Sub
Follow-up question
Sub Check2()
Dim rng1 As Range
Dim rng2 As Range
With Worksheets(1)
Set rng1 = .Range(.[D3:D4], .[D6:D14])
End With
On Error Resume Next
Set rng2 = rng1.SpecialCells(xlBlanks)
On Error GoTo 0
If Not rng1 Is Nothing Then
MsgBox rng1.Cells.Count - rng2.Cells.Count & " were used"
Else
MsgBox "all cells used"
End If
End Sub

Display message when cell is empty

Currently I managed to do for a single cell when the specified cell is empty then message / statement display on the cell.
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
If Range("AA17").Value = ISBLANK Then
Range("AA17").Value = "Please Specify"
End If
End Sub
What I would like to do is, for a several cell it will display the same thing. I can go ahead and do the same as above for all celsl but I have a few hundred cell to format it that way.
Is there a way to do so?
If the cells are contiguous, you could loop through them.
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Dim checkRng As Range
Dim cel As Range
Set checkRng = Range("A7:A70")
For Each cel In checkRng
If cel.Value = ISBLANK Then
cel.Value = "Please Specify"
End If
Next cel
End Sub
if there is any changes within the specified Range, the below code will run
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Dim Rng As Range
Dim wb As Workbook
Dim ws As Worksheet
Set wb = ThisWorkbook
Set ws = wb.ActiveSheet
Set Rng = ws.Range("A1:A100")
If Not Intersect(Target, Rng) Is Nothing Then
For Each Cell In Rng
If IsEmpty(Cell.Value) = True Then
Cell.Value = "Please Specify"
End If
Next
End If
Set Rng = Nothing
Set ws = Nothing
Set wb = Nothing
End Sub

Capture cell value with TextBox in UserForm

I have a UserForm which should be able to copy paste cells ideally. So firstly I would click the range I would want to copy, then activate the UserForm. The UserForm would have a combo box to choose which sheet I want to paste the data in, thereafter it would go to that sheet and user will click on the range or cell where he wants the data to be pasted.
I originally did an input box code to do this and it works perfectly, however when I do it in the UserForm it does not work as I am not able to incorporate the Type:=8 code in the textbox. Hence I would need some help on how can I enable my UserForm to paste cell data on the sheet, similarly to what I have done in application.inputbox.
This is the perfectly working code in the form of an input box:
Sub CopyPasteCumUpdateWithinSameSheet()
Dim rng As Range
Dim inp As Range
Selection.Interior.ColorIndex = 37
Set inp = Selection
On Error Resume Next
Set rng = Application.InputBox("Copy to", Type:=8)
On Error GoTo 0
If TypeName(rng) <> "Range" Then
Exit Sub
Else
inp.Copy
rng.Select
ActiveSheet.Paste Link:=True
'Cells(1,2).Font.ThemeColor =
End If
End Sub
This is the UserForm I have tried:
Dim Sh As Worksheet
Private Sub CommandButton1_Click()
On Error GoTo 0
If TypeName(rng) <> "Range" Then
Exit Sub
Else
inp.Copy
rng.Select
ActiveSheet.Paste Link:=True
End If
End Sub
Private Sub UserForm_Initialize()
CopyPasteUserform.Show vbModeless
For Each Sh In ThisWorkbook.Sheets
If Sh.Name <> "Inputs" Then
ComboBox1.AddItem Sh.Name
End If
Next
ComboBox1.Style = fmStyleDropDownList
End Sub
Private Sub ComboBox1_Change()
With ThisWorkbook.Sheets(ComboBox1.Text)
.Visible = xlSheetVisible
.Activate
End With
End Sub
Private Sub TextBox1_Change()
Dim rng As Range
Dim inp As Range
Selection.Interior.ColorIndex = 37
Set inp = Selection
On Error Resume Next
Set rng = TextBox.Value
End Sub
I tried incorporating the UserForm but all other functions stop responding apart from the RefEdit.
Dim Sh As Worksheet
Private Sub UserForm_Initialize()
CopyPasteUserform.Show vbModeless
For Each Sh In ThisWorkbook.Sheets
If Sh.Name <> "Inputs" Then
ComboBox1.AddItem Sh.Name
End If
Next
ComboBox1.Style = fmStyleDropDownList
Dim rng As Range
Dim inp As Range
Selection.Interior.ColorIndex = 37
Set inp = Selection
End Sub
Private Sub Combobox1_Change()
With ThisWorkbook.Sheets(ComboBox1.Text)
.Visible = xlSheetVisible
.Activate
End With
End Sub
Private Sub RefEdit1_Change()
Label1.Caption = ""
If RefEdit1.Value <> "" Then _
Label1.Caption = "[" & ComboBox1 & "]" & RefEdit1
Dim rng As Range
Dim inp As Range
On Error Resume Next
Set rng = RefEdit1.Value
On Error GoTo 0
If TypeName(rng) <> "Range" Then
Exit Sub
Else
inp.Copy
rng.Select
ActiveSheet.Paste Link:=True
End If
End Sub
You do not need the combobox to navigate to the sheets. That is the beauty of the Refedit
Is this what you are trying? I have not done any error handling. I am sure you can take care of that.
Create a userform and place 2 labels, 2 refedits and 1 commandbutton as shown below
Next paste this code in the userform code area
Code
Private Sub CommandButton1_Click()
Dim rngCopy As Range, rngPaste As Range
Dim wsCopy As Worksheet, wsPaste As Worksheet
If RefEdit1.Value <> "" And RefEdit2.Value <> "" Then
Set wsCopy = ThisWorkbook.Sheets(Replace(Split(RefEdit1.Value, "!")(0), "'", ""))
Set rngCopy = wsCopy.Range(Split(RefEdit1.Value, "!")(1))
Set wsPaste = ThisWorkbook.Sheets(Replace(Split(RefEdit2.Value, "!")(0), "'", ""))
Set rngPaste = wsPaste.Range(Split(RefEdit2.Value, "!")(1))
rngCopy.Copy rngPaste
Else
MsgBox "Please select Input and Output range"
End If
End Sub
In Action
The data will be copied from Sheet1!$A$1:$A$3 to Sheet2!$A$1:$A$3
Followup From Comments
However the pastelink feature has been missed out in the userform. Is it possible to incorporate it?:) – Niva 7 mins ago
Add a checkbox to the form as shown below
Use this code
Private Sub CommandButton1_Click()
Dim rngCopy As Range, rngPaste As Range
Dim wsCopy As Worksheet, wsPaste As Worksheet
If RefEdit1.Value <> "" And RefEdit2.Value <> "" Then
Set wsCopy = ThisWorkbook.Sheets(Replace(Split(RefEdit1.Value, "!")(0), "'", ""))
Set rngCopy = wsCopy.Range(Split(RefEdit1.Value, "!")(1))
Set wsPaste = ThisWorkbook.Sheets(Replace(Split(RefEdit2.Value, "!")(0), "'", ""))
Set rngPaste = wsPaste.Range(Split(RefEdit2.Value, "!")(1))
If CheckBox1.Value = True Then
wsPaste.Activate
rngPaste.Select
rngCopy.Copy
ActiveSheet.Paste Link:=True
Else
rngCopy.Copy rngPaste
End If
Else
MsgBox "Please select Input and Output range"
End If
End Sub
Description: Type:=8 will check that user input correct range name or not? In UserForm the TextBox not have this function. But we can detect this error when user click button. see my code.
No need to check when textbox is change, I delete code of textbox_change.
Replace below in your user form code area.
Option Explicit
Dim Sh As Worksheet
Dim inp As Range
Dim rng As Range
Private Sub CommandButton1_Click()
ActiveCell.Value = Me.TextBox1.Text
'On Error Resume Next
'If TypeName(Range(Me.TextBox1.Text)) <> "Range" Then
' MsgBox "Invalid range name!", vbCritical
' Exit Sub
'Else
' inp.Copy
' rng.Select
'
' ActiveSheet.Paste Link:=True
' MsgBox "Copy and paste finish.", vbInformation
'End If
'On Error GoTo 0
End Sub
Private Sub UserForm_Initialize()
For Each Sh In ThisWorkbook.Sheets
If Sh.Name <> "Inputs" Then
ComboBox1.AddItem Sh.Name
End If
Next
ComboBox1.Style = fmStyleDropDownList
End Sub
Private Sub ComboBox1_Change()
With ThisWorkbook.Sheets(ComboBox1.Text)
.Visible = xlSheetVisible
.Activate
End With
End Sub

Excel issue with integrating string text splitter function and worksheet_change

I'm trying to write a piece of code that automatically separates the data scanned in from a plug&play scanner from a 2D bar-code. The data is in this format "SN1234567 7654321 PA01234-5 A B C" and I need each block of text/numbers into each own cell. Now I was successful in finding a macro online to split this text(shown below), and also a macro to automatically run A (not my macro) macro when entering data into A1. the problem is I cant get the worksheet_change sub to work with my splittext macro. Code shown below
Private Sub Worksheet_Change(ByVal Target As Range)
Dim KeyCells As Range
' The variable KeyCells contains the cells that will
' cause an alert when they are changed.
Set KeyCells = Range("A1:C10")
If Not Application.Intersect(KeyCells, Range(Target.Address)) _
Is Nothing Then
' Display a message when one of the designated cells has been
' changed.
' Place your code here.
MsgBox "Cell " & Target.Address & " has changed."
Call textsplit
End If
End Sub
Sub textsplit()
Dim text As String
Dim a As Integer
Dim name As Variant
text = ActiveCell.Value
name = Split(text, " ")
For a = 0 To UBound(name)
Cells(1, a + 1).Value = name(a)
Next a
End Sub
It's not really clear where you want the split values to go, but something along these lines works:
Private Sub Worksheet_Change(ByVal Target As Range)
Dim KeyCells As Range, rng As Range
' The variable KeyCells contains the cells that will
' cause an alert when they are changed.
Set KeyCells = Range("A1:C10")
'Target can be a multi-cell range, so you need to account
' for that possibility
Set rng = Application.Intersect(KeyCells, Target)
If Not rng Is Nothing Then
' Display a message when one of the designated cells has been
' changed.
' Place your code here.
Debug.Print "Cell " & Target.Address & " has changed."
'prevent re-activating this sub when splitting text...
Application.EnableEvents = False
textsplit Target
Application.EnableEvents = True
End If
Exit Sub
haveError:
Application.EnableEvents = True
End Sub
Sub textsplit(rng As Range)
Dim c As Range, arr
For Each c In rng.Cells
If Len(c.Value) > 0 Then
arr = Split(c.Value, " ")
c.Offset(0, 1).Resize(1, UBound(arr) + 1).Value = arr
End If
Next c
End Sub
I modified some of your code to use TextToColumns instead of textsplit() which works.
Private Sub Worksheet_Change(ByVal Target As Range)
Dim KeyCells As Range
Set KeyCells = Range("A1:C10")
If Not Application.Intersect(KeyCells, Range(Target.Address)) _
Is Nothing Then
MsgBox "Cell " & Target.Address & " has changed."
Target.TextToColumns Destination:=Range(Target.Address), DataType:=xlDelimited, Space:=True
End If
End Sub
Once the cell was changed, the ActiveCell is no longer the target. Send the Sub the target, see below:
Private Sub Worksheet_Change(ByVal Target As Range)
Dim KeyCells As Range
' The variable KeyCells contains the cells that will
' cause an alert when they are changed.
Set KeyCells = Range("A1:C10")
If Not Application.Intersect(KeyCells, Range(Target.Address)) _
Is Nothing Then
' Display a message when one of the designated cells has been
' changed.
' Place your code here.
MsgBox "Cell " & Target.Address & " has changed."
Call textsplit(Target)
End If
End Sub
Sub textsplit(Target)
Dim text As String
Dim a As Integer
Dim name As Variant
text = Target.Value
name = Split(text, " ")
For a = 0 To UBound(name)
Cells(1, a + 1).Value = name(a)
Next a
End Sub

Excel VBA Event Handlers

1) Can someone please tell me what the issue could be with this code?
2) I need this code actually to run on a worksheet update, but # first-time load of the workbook, i'm running an update using the Workbook_Open event handler. Won't this trigger my Worksheet_Change event as well? Is there any way to avoid this
Private Sub Worksheet_Change(ByVal Target As Range)
Dim ws As Worksheet
Dim rowCount As Integer
Set Worksheet = "datasheet"
Set rowCount = ws.Cells(Rows.Count, "A").End(xlUp)
If Not Intersect(Target, Range("M3:M" & CStr(rowCount))) Is Nothing Then
MsgBox ("Hi")
End If
Else
If Not Intersect(Target, Range("T3:T" & CStr(rowCount))) Is Nothing Then
MsgBox ("Hi")
End If
Else
If Not Intersect(Target, Range("X3:X" & CStr(rowCount))) Is Nothing Then
MsgBox ("Hi")
End If
Else
If Not Intersect(Target, Range("AB3:AB" & CStr(rowCount))) Is Nothing Then
MsgBox ("Hi")
End If
Else
If Not Intersect(Target, Range("AI3:AI" & CStr(rowCount))) Is Nothing Then
MsgBox ("Hi")
End If
End Sub
I'm getting a Compiler error saying "object required" when i change my data with this handler. On the other hand, if i give values instead of taking a rowcount, I get no issues.
I always recommend this when using Worksheet_Change
You do not need the sheet name. It is understood that the code is to be run on current sheet unless you are trying to use another sheet row as a reference as correctly mentioned by brettdj in the comments below.
Whenever you are working with Worksheet_Change event. Always switch Off events if you are writing data to the cell. This is required so that the code doesn't go into a possible endless loop
Whenever you are switching off events, use error handling else if you get an error, the code will not run the next time.
Here is an example
Option Explicit
Private Sub Worksheet_Change(ByVal Target As Range)
On Error GoTo Whoa
Application.EnableEvents = False
'
'~~> Rest of the code
'
LetsContinue:
Application.EnableEvents = True
Exit Sub
Whoa:
MsgBox Err.Description
Resume LetsContinue
End Sub
So using the above, your code becomes (UNTESTED)
Private Sub Worksheet_Change(ByVal Target As Range)
Dim rowCount As Long
On Error GoTo Whoa
Application.EnableEvents = False
With ActiveSheet
rowCount = .Cells(.Rows.Count, "A").End(xlUp).Row
End With
If Not Intersect(Target, Range("M3:M" & rowCount)) Is Nothing Then
MsgBox ("Hi")
ElseIf Not Intersect(Target, Range("T3:T" & rowCount)) Is Nothing Then
MsgBox ("Hi")
ElseIf Not Intersect(Target, Range("X3:X" & rowCount)) Is Nothing Then
MsgBox ("Hi")
ElseIf Not Intersect(Target, Range("AB3:AB" & rowCount)) Is Nothing Then
MsgBox ("Hi")
ElseIf Not Intersect(Target, Range("AI3:AI" & rowCount)) Is Nothing Then
MsgBox ("Hi")
End If
LetsContinue:
Application.EnableEvents = True
Exit Sub
Whoa:
MsgBox Err.Description
Resume LetsContinue
End Sub
EDIT:
Regarding your 2nd question. As I mentioned in the comment above, you can use a Public variable to check if the worksheet change event is being caused by the workbook open.
Place this code in a module.
Public WasWbOpened As Boolean
Place this code in the workbook code area
Option Explicit
Private Sub Workbook_Open()
WasWbOpened = True
'
'~~> Rest of the code
'
WasWbOpened = False
End Sub
And change your worksheet change event to
Private Sub Worksheet_Change(ByVal Target As Range)
If WasWbOpened = True Then Exit Sub
Dim rowCount As Long
On Error GoTo Whoa
Application.EnableEvents = False
With ActiveSheet
rowCount = .Cells(.Rows.Count, "A").End(xlUp).Row
End With
If Not Intersect(Target, Range("M3:M" & rowCount)) Is Nothing Then
MsgBox ("Hi")
ElseIf Not Intersect(Target, Range("T3:T" & rowCount)) Is Nothing Then
MsgBox ("Hi")
ElseIf Not Intersect(Target, Range("X3:X" & rowCount)) Is Nothing Then
MsgBox ("Hi")
ElseIf Not Intersect(Target, Range("AB3:AB" & rowCount)) Is Nothing Then
MsgBox ("Hi")
ElseIf Not Intersect(Target, Range("AI3:AI" & rowCount)) Is Nothing Then
MsgBox ("Hi")
End If
LetsContinue:
Application.EnableEvents = True
Exit Sub
Whoa:
MsgBox Err.Description
Resume LetsContinue
End Sub
You have several issues
As per Sid's comment you should use rowCount = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
You should be using Set ws = Sheets("datasheet") not Set Worksheet = "datasheet"
Your Else statements are causing errors as they are orphaned. If you want to exit on the first "Hi" rather than continuing to test you should try something like this
Sid has covered your other point. You can use a Boolean variable for this
updated code
this tests the intersect on columns M, T, X, AB and AI from row 3 to row rowCount in a single line
Private Sub Worksheet_Change(ByVal Target As Range)
Dim ws As Worksheet
Dim rowCount As Long
Set ws = Sheets("datasheet")
rowCount = ws.Cells(Rows.Count, "A").End(xlUp).Row
If Not Intersect(Target, Range("M3:M" & CStr(rowCount) & ",T3:T" & CStr(rowCount) & ",X3:X" & CStr(rowCount) & ",AB3:AB" & CStr(rowCount) & ",AI3:AI" & CStr(rowCount))) Is Nothing Then MsgBox ("Hi")
End Sub