VBA - Filling a cell value after a combobox text is entered/changed - vba

I have the following piece of code on my workbook on my sheet, which is intended to test intersection using ws change and then go to the combo box and retrieve whatever value is entered in the box. However, what is happening is that after the value is entered in the combo box the first time the cell isn't updating with it's value. I have to click it again, and then it will populate. I know I have to likely use another event procedure, but I have no clue about combo box events. Can someone point me in the right direction?
Thx Mike.
Option Explicit
Private Sub Worksheet_Change(ByVal Target As Range)
Dim aRng As Range
Dim tRng As Range
Set aRng = Range("C19:C36")
Set tRng = Sheet2.Range("I2")
Application.EnableEvents = False 'to prevent re-iteration of event
On Error GoTo cleanup:
If Not Intersect(aRng, Target) Is Nothing Then
Call Sheet2.ComboBox1_Change
Target.Value = Sheet2.ComboBox1.Value
End If
cleanup: 'enable events once again
Application.EnableEvents = True
End Sub
and on Sheet 2 where the box is.
Public Sub ComboBox1_Change()
With ComboBox1
.Activate
.SelText = Empty
.DropDown
.MatchRequired = True
End With
End Sub

To get to the basics of your question, the Combobox has a LinkedCell property. If you enter the cell address on Sheet1 there, the selected item in the ComboBox will be displayed on Sheet1. (If a value is entered in that Cell on Sheet1, it will also be displayed in the ComboBox.)
ComboBox LinkedCell
You can force Sheet1 to be displayed after a selection is made in the ComboBox with this code (in the module of Sheet2):
Private Sub ComboBox1_Change()
Sheet1.Select
End Sub
Using Worksheet_Change will only have effect AFTER something has been entered into the cell (and RETURN has been hit).

Related

BeforeDoubleClick code placing data based on where cursor currently exists

I may or may not have an easy one here... For some reason I can't properly think of the solution.
Spreadsheet has numbers 1 to 14 in column A. 14 ends on row 15 as there is a header in cell A1. What I'm trying to do is double click one of these numbers and transfer that number to a specific cell on the same sheet (named "Sheet1"). I was able to put the code together to make it work for transferring a chosen number to a specific cell. Code below works well. However, I don't want to add a bunch of areas to double click for different cells. For example: The destination cell for the chosen data is E6, H6, and G6. I'd like to place the cursor starting in E6, double click a number in range A2 to A15, and have that number that I choose between A2 and A15 to appear in E6 since that is where the cursor was when I double clicked a cell in A2 to A15. Then I would move the cursor by click H6 and then going back to same selection between A2 to A15, placing whatever number I choose in that range in H6 since that is where the cursor currently exists.
Hopefully this makes sense and is even possible.
example screenshot
Working code that allows the double click to put data in a certain cell
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
If Not Intersect(Target, Range("A2:A15")) Is Nothing Then
Cancel = True
Target.Copy Destination:=Cells(6, "E")
End If
End Sub
I've added the solution I would try, with comments in the code. The reason for two sheet variables, is because the first click in the double-click registers as a SelectionChange event. So to get the correct cell location, you need it from two selections back, instead of just one.
Public selectedCell As String 'Sheet Variable
Public lastCell As String
' This updates the Sheet variable with the most recent selection
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
selectedCell = lastCell
lastCell = Target.Address
End Sub
' Added a check for having a previously selected cell
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
If Not Intersect(Target, Range("A2:A15")) Is Nothing Then
If selectedCell = vbNullString Then
Cancel = True
MsgBox "Please select a destination cell for the data."
selectedCell = vbNullString
lastCell = vbNullString 'Prevents overwriting same cell by accident
Else
Cancel = True
Target.Copy Destination:=Range(selectedCell)
selectedCell = vbNullString
lastCell = vbNullString 'Prevents overwriting same cell by accident
End If
End If
End Sub
Here is a tiny tool that you may be able to adapt to your needs. If you double-click on an empty cell, it becomes the FinalDestination. If you then double-click on another cell that is not empty, its contents will be copied to FinalDestination:
In the worksheet code area:
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
Cancel = True
Application.EnableEvents = False
If Target.Value = "" Then
Set FinalDestination = Target
Else
Target.Copy FinalDestination
End If
Application.EnableEvents = True
End Sub
In a standard module:
Public FinalDestination As Range
NOTE:
In this simple demo code there are no restrictions on source/destination.

excel hide rows with error values based on dropdown change

I would like to hide rows in column B9-B40 when Index/Match formula returns "N/A" , now I managed to get it done in VBA when the table is static but I have a dynamic table based on drop-down selection which means the number of N/As returned can be different for each time drop-down selection changes.
Here is what I have right now which hides the rows with N/A based on current drop-down selection, my dropdowns are in C2,C3 and C4. But it doesn't takes any further change in the dropdown into consideration afterwards. I am not very competent with the VBA so any help would be great.
Thanks.
Option Explicit
Sub hide_if_error()
Dim MyCell As Range, Rng As Range
Set Rng = Range("B9:B40")
For Each MyCell In Rng
If IsError(MyCell) Then
MyCell.EntireRow.Hidden = True
End If
Next MyCell
End Sub
You can do
Range("B9:B40").SpecialCells(xlCellTypeFormulas, xlErrors).EntireRow.Hidden = True
You will need a test in advance that errors are present though.
That might look like:
Option Explicit
Public Sub hide_if_error()
With ThisWorkbook.Worksheets("Sheet4")
.Range("B9:B40").EntireRow.Hidden = False
If Evaluate("=SUM(IF(ISERROR(" & .Range("B9:B40").Address & "),1))") > 0 Then '<==check if any errors present
.Range("B9:B40").SpecialCells(xlCellTypeFormulas, xlErrors).EntireRow.Hidden = True
End If
End With
End Sub
If necessary, you could link the above to a worksheet change or dropdown change event so it is fired each time there is an update using the dropdown(s)
For example:
If you data validation was in C2:C4 you would put in the code pane for the sheet the following event code:
Option Explicit
Private Sub Worksheet_Change(ByVal Target As Range)
On Error GoTo ErrHand
If Not Intersect(Target, Range("C2:C4")) Is Nothing Then
Application.EnableEvents = False
hide_if_error
End If
ErrHand:
Application.EnableEvents = True
End Sub
Note:
The worksheet event code goes in the code pane associate with sheet 4:
The other code goes in a standard module (module 1 here):
Example run:

How do I hide a sheet with a button in Excel?

I would like to create a button to hide the sheet. Ideally, it would hide the sheet where the button is located.
To be simple, sheet 1 has a form to fill out. The typical name, address, phone number, etc. Sheet 2 and 3 also have the same fields that is going to be referenced to the 'Data' tab as well. On a sheet named 'Data', I will add fields that will populate simply with the = option like (=Data!...)
However, I do not want the Data page in view once the information is added. We all know the simple right click and hide sheet. But sometimes that's too much for some people that will use this sheet and a pretty button would work better.
I was successful using:
Module 1
Sub SheetCommand()
If Worksheets("Sheet1").Range("C2").Value <> vbNullString Then
Worksheets("Sheet2").Visible = False
Else
Worksheets("Sheet2").Visible = True
End If
End Sub
Sheet1 Code:
Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Address <> "$C$2" Then Exit Sub
Run "SheetCommand"
End Sub
However, I am not very VB savvy and have hit a dead end. Could someone help show me how to apply this to a button? I don't want it to reference the $C$2 field as noted on the example, but just when someone presses the button, the sheet goes away. I'm not worried about getting it back as someone can be ready to get it the old fashioned way. This would help the data entry process for this manual form so much easier.
Edit: basically, I need help creating a vba code where I can hide the page. I'd like to create a button where once clicked, it hides that page. I showed an example of a code where I got it to work but it only works if that cell is populated. How do I make it work on button click?
I found this code that does what I need but I would like to tell it a specific Sheet Name instead of having to type it in B6 and B7.
Sub ShowHideWorksheets()
Dim Cell As Range
For Each Cell In Range("B6:B7")
ActiveWorkbook.Worksheets(Cell.Value).Visible = Not
ActiveWorkbook.Worksheets(Cell.Value).Visible
Next Cell
End Sub
It's actually not very clear to me what's your exact goal
for instance, assuming "Sheet 2" and "Sheet2" would point to the same sheet, in your question you seem to reference it as being both a "Form" sheet ("...sheet 1 has a form to fill out....Sheet 2 and 3 also have the same fields...") and "Data" sheet (Worksheets("Sheet2").Visible = False)
so here follow some possible solutions:
1) you want to hide "Data" sheet before closing the workbook it's contained in
then place the following code in "ThisWorkbook" code pane of the workbook containing "Data" sheet
Private Sub Workbook_BeforeClose(Cancel As Boolean)
ThisWorkbook.Worksheets("Data").Visible = False
End Sub
2) you want to hide "Data" sheet once some cells have been filled up in ANY sheet other than "Data"
then place the following code in "ThisWorkbook" code pane of the workbook containing "Data" sheet
Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
If Sh.Name <> "Data" Then
With Sh
'here follows code to check if "the information is added"
'for instance:
If WorksheetFunction.CountA(.Range("A2:C2")) = .Range("A2:C2").Count Then ThisWorkbook.Worksheets("Data").Visible = False 'check if all cells in range "A2" to "C2" has been filled with some data
End With
End If
End Sub
3) you want to hide "Data" sheet once some cells have been filled up in ALL sheets other than "Data"
then place the following code in "ThisWorkbook" code pane of the workbook containing "Data" sheet
Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
Dim sht As Worksheet
Dim hideBool As Boolean: hideBool = True 'set initial value as true
If Sh.Name <> "Data" Then
For Each sht In ThisWorkbook.Worksheets
With Sh
'here follows code to check if "the information is added"
'for instance:
hideBool = hideBool And WorksheetFunction.CountA(.Range("A2:C2")) = .Range("A2:C2").Count ''check if all cells in range "A2" to "C2" of current sheet has been filled with some data
End With
If Not hideBool Then Exit For
Next sht
ThisWorkbook.Worksheets("Data").Visible = Not hideBool ' hide if ALL sheets met "information is added" condition
End If
End Sub
4) otherwise give more info about the desired behavior

Adding a formula dynamically to an excel cell

Is there a way (VB?) to add a formula dynamically to an excel cell?
I have a cell with conditions true and false, and they change based on a checkbox.
And I have another cell, which has a formula in it. This formula should be used if the checkbox is unchecked.
If the checkbox is checked, then user should be able insert value manually (without any formula prompting there).So the formula should not be there.
I was thinking of a solution where I would add the formula to the cell if checkbox is unchecked, and then if the checkbox is checked, then I would clear the cell.
How could this be done? I'm not very familiar with excel coding and VBA.
Ok you need a trigger on TRUE/FALSE cell to execut the next VBA code,
right click on sheet name and click "View Code" and enter this code:
Private Sub Worksheet_Change(ByVal Target As Range)
If Not Intersect(Target, Range("A5:A5")) Is Nothing Then 'define adress of your True/Flase cell
If Target.Cells.Value = False then
Range("B5").formula = "=enter your formula" 'define adress for cell with formula aswell
else
Range("B5").value = ""
end if
end if
end sub
well you could use:
if userform1.checkbox.checked = false then
range("A1").formula = "=myformula"
else
range("A1").value = ""
end if
you need to insert the code into the userform checkbox click or change event both should have same effect, just double click on the checkbox in userform and it will take you to the click event or replace the click with "change", hope that's what you meant to achieve, cheers
PS. thanks for suggestions #99moorem
If you have a classical Excel CheckBox, you can add a Linked Cell which will be True or False.
In the following code, your Linked Cell is in A1, the cell with the formula to use in B1 and the cell that need to be empty or filled by formula is in C1.
You'll need to specify the Sheet_Name (can be differents) and place that code directly into the Sheet "module" in VBA (press Alt+F11 and double-click on the sheet (in the left panel) with the Linked Cell, then just paste and edit regarding your specifications)
Private Sub Worksheet_Change(ByVal Target As Range)
Dim LinkedCell As Range, _
FormulaCell As Range, _
ChangingCell As Range
Set LinkedCell = Sheets("Sheet_Name").Range("A1")
Set FormulaCell = Sheets("Sheet_Name").Range("B1")
Set ChangingCell = Sheets("Sheet_Name").Range("C1")
If Application.Intersect(Target, LinkedCell) Is Nothing Then
'not in linked cell
Else
'in linked cell
If LinkedCell.Value2 <> True Then
'Unchecked
ChangingCell.FormulaLocal = ChangingCell.FormulaLocal
Else
'Checked
ChangingCell.FormulaLocal = vbNullString
End If
End If
Set LinkedCell = Nothing
Set FormulaCell = Nothing
Set ChangingCell = Nothing
End Sub

Excel VBA: Get range of previous cell after calling LostFocus()

How can I get the range of a previous cell in Excel? I have a ComboBox and usually I can fill its value into the active cell (under the ComboBox) with ActiveCell.Value = box.Value. When I have selected a value of my ComboBox and click in any other cell, I want the value of the ComboBox to be written into the previous cell, but this code writes it to cell I clicked on:
Private Sub box_LostFocus()
ActiveCell.Value = box.Value
End Sub
Any ideas?
If you include this in your worksheet code, PreviousCell will always be the previous range you had selected.
Dim PreviousCell As Range
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
' Your code that uses PreviousCell should go in the if statement that makes sure PreviousCell has a value
If Not PreviousCell Is Nothing Then
Debug.Print PreviousCell.Address
End If
Set PreviousCell = Target ' This needs to be the last line of code.
End Sub