I'm currently developing an add-in for Excel which will automatically format a table. The users has to follow the specific format when preparing the table, or else the common error of "Merging cells only keeps the upper-left cell value, and discards the other values." is bound to appear.
I would like to mute this alert from Excel, but would still like to catch this error and pass a different message to the users to terminate this sub. I've tried this:
Sub FormatTable()
On Error Goto ErrHandler
Application.DisplayAlerts = False
'Codes for formatting the table
Exit Sub
ErrHandler:
MsgBox "Incorrect formatting. Terminating process to conserve data."
End Sub
However, I do realise that using "Application.DisplayAlerts = False" will cause Excel to choose the default action and proceed to merge the cells which causes a big mess. It will not go the ErrHandler. Is there some way for making this happen? Thank you.
You could test for merged cells in the selected range prior to running your code:
Public Function HasMergedCells(oRng As Range)
Dim oCell As Range
Dim oArea As Range
For Each oArea In oRng.Areas
For Each oCell In oArea.Cells
If oCell.MergeArea.MergeCells Then
HasMergedCells = True
Exit Function
End If
Next
Next
End Function
Related
I've created a drop down menu through data validation for workbook navigation. The following is a snippet of code I have for the drop down box to change worksheets in the workbook:
Private Sub Worksheet_Change(ByVal Target As Range)
On Error Resume Next
If Not (Application.Intersect(Range("J4"), Target) Is Nothing) Then _
ThisWorkbook.Sheets("Home").Visible = False
ThisWorkbook.Sheets(Target.Value).Activate
ThisWorkbook.Sheets(Target.Value).Visible = True
ThisWorkbook.Sheets("Imported Data").Visible = False
End Sub
The code is meant to hide all other worksheets that are accessible by the drop down list besides the one selected. I have about 10 tabs and this code has worked perfectly to achieve the basic goal of navigation. However, some pages have formulas and when you update data in the cells meant for calculations the workbook jumps to a random worksheet in the workbook that is not at all referenced in this sub.
Is there some way to have my worksheets not try to do anything with this sub unless the dropdown menu itself is changed?
Bonus (less important) Question: is there a way to make the drop box default to (blank) unless the menu itself is accessed?
Then _
The space followed by an underscore _ means that the current statement isn't finished yet but continues on the next line. Right now the last 3 lines will run whenever there is a change in the worksheet. Put the entire code in If-Endif.
Also avoid unnecessary use of On Error Resume Next. Use proper error handling.
You need to make the sheet visible before you activate it and not vice versa.
Try this
Private Sub Worksheet_Change(ByVal Target As Range)
On Error GoTo Whoa
If Not (Application.Intersect(Range("J4"), Target) Is Nothing) Then
ThisWorkbook.Sheets("Home").Visible = False
ThisWorkbook.Sheets(Target.Value).Visible = True
ThisWorkbook.Sheets(Target.Value).Activate
ThisWorkbook.Sheets("Imported Data").Visible = False
End If
Letscontinue:
Exit Sub
Whoa:
MsgBox Err.Description
Resume Letscontinue
End Sub
is there a way to make the drop box default to (blank) unless the menu itself is accessed?
If you have created it with Data Valdation then insert a blank value in the list.
I want to update a normal filter when a cell within the filter is calculated.
I have a list in the range A2:A10, if it displays 1 then show the row, if it's 0 then hide the row. In the range A2:A10 I have formulas which calculates if it should be 0 or 1. I only need to update the filter if the value change and I do this with this VBA:
Private Sub Worksheet_Calculate()
Dim RG As Range
Set RG = Range("A2:A10")
If Not Intersect(RG, Range("A2:A10")) Is Nothing Then
ActiveSheet.Range("$A$1:$B$10").AutoFilter Field:=1, Criteria1:="1"
End If
End Sub
But whenever the macro runs, excel freezes. I believe this is because a loop is created which never stops. When the filter is updated, that will cause the macro to run again.
I only need it to update the filter when the value in the range is changed, but it updates the filter when the filter is updated, which will update the filter again. So, a loop is created which causes excel to freeze.
I also get a:
run-time error '-2147417848 (80010108)':
Automation error
The object invoked has disconnected from its clients.
Some suggestions on your code:
Add EnableEvents = false so nothing else is triggered by the changes you make with the macro (and reenable them at the end of the procedure)
Name your variables to something meaningful e.g. targetRange instead of RG
Use at least a basic error handling On error Goto
As you have this code behind a Worksheet you can refer to that worksheet as Me instead of ActiveSheet
About the logic:
This line is redundant
If Not Intersect(targetRange, Me.Range("A2:A10")) Is Nothing Then
You are defining the range as Range("A2:A20")
Set targetRange = Me.Range("A2:A10")
I left it so you can change it to whatever you want to check
Refactored code:
Private Sub Worksheet_Calculate()
On Error GoTo CleanFail
' Disable events so nothing else is triggered by the changes you make with the macro
Application.EnableEvents = False
Dim targetRange As Range
Set targetRange = Me.Range("A2:A10")
' This next line doesn't make sense, you're comparing the same ranges
If Not Intersect(targetRange, Me.Range("A2:A10")) Is Nothing Then
Me.Range("$A$1:$B$10").AutoFilter Field:=1, Criteria1:="1"
End If
CleanExit:
' Reenable events
Application.EnableEvents = True
Exit Sub
CleanFail:
MsgBox "Error: " & Err.Description
GoTo CleanExit
End Sub
Let me know if you have any questions.
I've got worksheets that users will be hiding/unhiding columns on for printing purposes. Within those columns are certain cells which need to be copied to a visible area when those columns are hidden and the process reversed when they are not. The function works fine to detect the columns' visible status when the worksheet is activated. However it does not update at the time the column statuses are changed. I understand that the worksheet_calculate sub will detect changes in row visibility, but not columns, nor does it work in worksheet_change. Worksheet_SelectionChange seems buggy (selects more than selected even without code). Suggestions?
Public Function Copy_Hidden_ChargeCode_Descriptions(ByRef sht As String)
On Error GoTo ErrorHandler
Application.EnableEvents = False
If Worksheets(sht).Columns("C:G").Hidden = False Then
If Not IsEmpty(Worksheets(sht).Range("H4")) Then
Worksheets(sht).Range("H1").Cut Worksheets(sht).Range("C1")
Worksheets(sht).Range("H4:N9").Cut Worksheets(sht).Range("C4:H9")
End If
Else
If IsEmpty(Worksheets(sht).Range("H4")) Then
Worksheets(sht).Range("C1").Cut Worksheets(sht).Range("H1")
Worksheets(sht).Range("C4:H9").Cut Worksheets(sht).Range("H4:N9")
End If
End If
Application.EnableEvents = True
Exit Function
ErrorHandler:
Debug.Print Err.Number, Err.Description
End Function
I have a macro which is basically working as I want (alerting the user when two conflicting checkboxes are selected) - code below. The 1 in G2 is the value generated to indicate this case.
The error message fires on SelectionChange, but this appears to be only when another cell is selected by mouse. The worksheet contains a series of checkboxes for the user to select from, and the intention is for the user to only use the checkboxes, never needing to select or input directly into cells. In which case, the error message would never fire even when the scenario described has occurred.
Is there a way of having a msgbox macro trigger by the update of any checkbox on the sheet?
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
If Range("G2") = 1 Then
MsgBox "ERROR - Select AND Reject checked"
End If
End Sub
Also, I would like to extend the range to apply to all the cells in column G, I just can't seem to get this to work for me. I have seen a few examples citing "G:G" but I have so far only got this to work for one cell.
Apologies in advance for any glaring errors, I've used Excel for a while now - but I'm brand new to using VBA.
Mutually exclusive options are usually indicated with option buttons (also known as radio buttons) instead of checkboxes. Is there any reason you're not using option buttons for this task?
As far as calling the same code for all checkboxes, the checkboxes would have to be Form Controls (not ActiveX Controls), and you could assign them to this macro:
Sub CheckBox_Clicked()
Dim chk As CheckBox
Set chk = ActiveSheet.CheckBoxes(Application.Caller)
MsgBox chk.Name
End Sub
And lastly, for your SelectionChange event to monitor an entire column, it would look similar to this:
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Dim ClickedCell As Range
Dim rngClicked As Range
Application.EnableEvents = False
Set rngClicked = Intersect(Columns("G"), Target)
If Not rngClicked Is Nothing Then
For Each ClickedCell In rngClicked.Cells
If ClickedCell.Value = 1 Then MsgBox "ERROR - Select AND Reject checked"
Next ClickedCell
End If
Application.EnableEvents = True
End Sub
i have an excel with 75 columns and some thousands of rows of data. Out of 75 columns I am using 5 columns for my vba coding purpose. These 5 columns hold flags (either 0 or 1) based on which I am locking the cells in the corresponding row (Flags are coming from Database). As user doesn't want these flag columns I just hid those columns but when ever user tries to copy data from my workbook to another workbook user is able to copy the hidden columns which client doesn't want.
So is there anyway to restrict them not to copy the hidden columns through VBA or with any setting? Actually for this issue what I thought is like on key press of Ctrl + C, I tried to change the Selection.Copy as Selection.Range.SpecialCells(xlCellTypeVisible). But I am getting some error like wrong number of arguments or invalid property assignment.
The lines of code is
Private Sub Workbook_Open()
Application.OnKey "^c", "Copy"
End Sub
Sub Copy()
If Selection Is Nothing Then
Else
Selection.Copy = Selection.Range.SpecialCells(xlCellTypeVisible)
End If
End Sub
Any ideas to restrict users not to copy the hidden columns. Any help would be appreciated greatly.
Try this
Sub Copy()
Dim rng As Range
On Error GoTo Whoa
If Not Selection Is Nothing Then
Set rng = Selection.Cells.SpecialCells(xlCellTypeVisible)
rng.Copy
End If
LetsContinue:
Exit Sub
Whoa:
MsgBox Err.Description, vbCritical, "Error Number : " & Err.Number
Resume LetsContinue
End Sub
Note: I have used Error Handling which is a must because the user might select non contiguous ranges and the code will break if the error handling is not done :) See Screenshot below