Situation: I'm working on a UserForm with the following Controls:
Combobox: This is used to pull up a list of names on Sheet2 (Column A) and allows the user to select a name that'll be used for the form.
TextBox: This is used to add a numerical value. That value will be placed on Sheet2, Column C, and two rows over from the name that's been selected from the combo box
CommandButton: This button is used to add the numerical value that has been typed into the text box into the cell on Sheet2, two columns over, and two rows over from the cell matching the name that's been choosen from the combobox
Problem: I have the Combobox and Textbox set up correctly but am having trouble creating VBA for the CommandButton to add the text box value to it's destination.
VBA So Far:
Private Sub AddButton_Click()
Dim WS As Worksheet
Dim Rng As Range
Dim Crystal As Long
Set WS = Worksheets("ParticipantList")
With WS.Range("a2:c300")
FindColumn = Application.WorksheetFunction.Match(Me.Participants.Value, WS.Range("A2:A300"), 1)
Crystal = Me.NumberOfCryst.Value
If FindColumn <> "" Then
With WS.Range("a2:c300")
Text = Me.NumberOfCryst.Value
WS.Activate
FindColumn = Application.WorksheetFunction.Match(Me.Participants.Value, WS.Range("A2:A300"), 0)
End With
End If
End With
End Sub
Now obviously this is all over the place and I've made tons of changes and attempts at getting it to work.
maybe you're after something like this:
Private Sub AddButton_Click()
Dim Rng As Range
Set Rng = Worksheets("ParticipantList").Range("A2:A300").Find(What:=Me.Participants.Value, LookIn:=xlValues, lookat:=xlWhole)
If Not Rng Is Nothing Then Rng.Offset(2, 2).Value = Rng.Offset(2, 2).Value + CLng(Me.NumberOfCryst.Text)
End Sub
you may also want to add some textbox text validation and be sure the user input a numeric value
Related
I want to be able to create a button function macro to update stock values based upon one cell that contains the new value and another that identifies the physical cell address.
Very new to VBA and only have a basic understanding
I have tried the below:
Private Sub CommandButton1_Click()
Dim rng As Range
rng = Range(Range("m2").Value2).Select
Set rng.Value = Range("k2").Value
End Sub
So what I want to happen is that when clicking the command button the value in the cell determined by the cell address in M2 is updated to the value in cell K2.
Please help a complete noob trying to learn.
You Set Objects not values:
Private Sub CommandButton1_Click()
Dim rng As Range
Set rng = ActiveSheet.Range("m2")
rng.Value = ActiveSheet.Range("k2").Value
End Sub
Some logic to my process:
In column K on my worksheet I have inserted check boxes from cell K3 - K53 (this could become longer in the future) using the developer tab.
I then associated the check box with the same cell it is placed in.
I formatted the cells in this column by going to 'Format Cells', clicking on 'Custom' then typing in ';;;'. This was to HIDE the 'True/False' text from view.
My next step is to change the cell colour based on the text.
Note:
I have searched through a few forums and combined some code samples from them all, so I will not be able to reference the sources exactly, but below is what I have so far:
Code:
Sub Change_Cell_Colour()
Dim xName As Integer
Dim xChk As CheckBox
Dim rng As Range
Dim lRow As Long
lRow = ActiveWorksheet.Cells(Rows.Count, "B").End(xlUp).Row
Set rng = ActiveWorksheet.Range("K2:K" & lRow)
For Each xChk In ActiveSheet.CheckBoxes
xName = Right(xChk.Name, Len(xChk.Name) - 10)
If (Range(xChk.LinkedCell) = "True") Then
rng.Interior.ColorIndex = 6
Else
rng.Interior.ColorIndex = xlNone
End If
Next
End Sub
I keep getting an error on the line where I try to get the last row.
Code:
lRow = ActiveWorksheet.Cells(Rows.Count, "B").End(xlUp).Row
Error:
Object Required
I am not even sure if the code I have will solve my issue, so any help solving the main issue highlighting a cell based on the check box being checked or not, will be greatly appreciated.
Here's a quick rewrite with LOTS of comments explaining:
Sub Change_Cell_Colour()
Dim xChk As CheckBox
'Be explicit about which worksheet. Leaving it to "Activeworksheet" is going to cause problems
' as we aren't always sure which sheet is active...
'Also in this case we don't need to know the last row. We will iterate checkbox objects, not
' populate rows.
'lRow = ActiveWorksheet.Cells(Rows.Count, "B").End(xlUp).Row
'Again... we don't need this. We just need to iterate all the checkboxes on the sheet
'Set rng = ActiveWorksheet.Range("K2:K" & lRow)
'This is good stuff right here, just change the ActiveSheet to something more explicit
' I've changed this to the tab named "Sheet1" for instance.
For Each xChk In Sheets("Sheet1").CheckBoxes
'Getting the name of the checkbox (but only the last 10 characters)
xName = Right(xChk.Name, Len(xChk.Name) - 10)
'We can check the linked cell's value, but we can also just check if the
' if the checkbox is checked... wouldn't that be easier?
'If (Range(xChk.LinkedCell) = "True") Then
If xChk.Value = 1 Then
'Now we can use the "LinkedCell", but it's a STRING not a RANGE, so we will have
' to treat it as the string name of a range to use it properly
Sheets("Sheet1").Range(xChk.LinkedCell).Interior.ColorIndex = 6
Else
Sheets("Sheet1").Range(xChk.LinkedCell).Interior.ColorIndex = xlNone
End If
Next
End Sub
Here's the barebones version just to get it working
Sub Change_Cell_Colour()
Dim xChk As CheckBox
'Loop through each checkbox in Sheet1. Set it to color 6 if true, otherwise no color
For Each xChk In Sheets("Sheet1").CheckBoxes
If xChk.Value = 1 Then
Sheets("Sheet1").Range(xChk.LinkedCell).Interior.ColorIndex = 6
Else
Sheets("Sheet1").Range(xChk.LinkedCell).Interior.ColorIndex = xlNone
End If
Next
End Sub
I'm totally assuming here, but I would imagine you want this macro to fire when a checkbox is clicked. There is a handy Application.Caller that holds the name of the object that caused a macro to be called. You can set the "Assign Macro.." of each checkbox to this new code and then you can figure out which checkbox called the subroutine/macro using application.caller and follow the same logic to toggle it's linked cell color:
Sub Change_Cell_Colour()
Dim xChk As CheckBox
'Who called this subroutine/macro?
Dim clickedCheckbox As String
clickedCheckbox = Application.Caller
'Lets check just this checkbox
Set xChk = Sheets("Sheet1").CheckBoxes(clickedCheckbox)
'toggle its color or colour if you are a neighbour
If xChk.Value = 1 Then
Sheets("Sheet1").Range(xChk.LinkedCell).Interior.ColorIndex = 6
Else
Sheets("Sheet1").Range(xChk.LinkedCell).Interior.ColorIndex = xlNone
End If
End Sub
highlighting a cell based on the check box being checked or not
Select the sheet and apply a CF formula rule of:
=A1=TRUE
ActiveWorksheet doesn't exist, and because you haven't specified Option Explicit at the top of your module, VBA happily considers it an on-the-spot Variant variable.
Except, a Variant created on-the-spot doesn't have a subtype, so it's Variant/Empty.
And ActiveWorksheet.Cells being syntactically a member call, VBA understands it as such - so ActiveWorksheet must therefore be an object - but it's a Variant/Empty, hence, object required: the call is illegal unless ActiveWorksheet is an actual Worksheet object reference.
Specify Option Explicit at the top of the module. Declare all variables.
Then change ActiveWorksheet for ActiveSheet.
I was playing around with a userform where I have a TextBox and ComboBox.
Now my aim is to start writing a Name in the TextBox while in the meantime have list of suggestions of Names (stored in a database) which filter out with every letter I type in the text box.
An example would be writing "N..." in the TextBox and having a ComboBox with suggestions "Nick, Nathan, etc."
Does anyone have any ideas, I was banging my head around this for a while.
Thank you!
You may try something like this...
Place the following code on UserForm Module.
The code assumes you have a sheet called Data in the workbook and two controls named TextBox1 and ComboBox1 on the UserForm.
Private Sub TextBox1_Change()
Dim wsData As Worksheet
Dim x, dict
Dim i As Long
Set wsData = Sheets("Data") 'Sheet with data
Set dict = CreateObject("Scripting.Dictionary")
'Clearing the combobox
Me.ComboBox1.Clear
If TextBox1.Value <> "" Then
x = wsData.Range("A1").CurrentRegion.Value
'Assuming the ComboBox will have items from column A of data sheet
'Assuming Row1 is the header row
For i = 2 To UBound(x, 1)
If LCase(Left(x(i, 1), 1)) = LCase(Left(TextBox1.Value, 1)) Then
dict.Item(x(i, 1)) = ""
End If
Next i
Me.ComboBox1.List = dict.keys
End If
End Sub
I have a userform for Excel that has a listbox for employee names. I'm sourcing the options from column A of an Excel worksheet so it can auto-complete entries in the userform based on past entries. The problem is that there are multiple rows of entries in the worksheet for each employee and I would like to only have one of each names in the drop-down list.
The code to populate the listbox is:
Private Sub UserForm_Initialize()
Me.txtName.List = Worksheets("Sheet1").Range("A6:A600").Value
Is there a way to do this?
If ListBox1.Range.Value...?
The below code uses a helper Dictionary object to determine if items have been added to the ListBox, and if not, it adds them. It also dynamically selects the range of names based on a starting cell of A6 and moving down the spreadsheet to the first break in data. If there are breaks that you want to ignore, please let us know.
I used the AddItem method of the ListBox instead of the List property.
Private Sub UserForm_Initialize()
Dim rNames As Range
Dim oDict As Object
Dim cel As Range
Set rNames = Worksheets("Sheet1").Range("A6:A" & Worksheets("Sheet1").Range("A6").End(xlDown).Row)
Set oDict = CreateObject("Scripting.Dictionary")
For Each cel In rNames
If oDict.exists(cel.Value) Then
'Do nothing for now
Else
oDict.Add cel.Value, 0
Me.txtName.AddItem cel.Value
End If
Next cel
End Sub
I have a very complex workbook with many tabs. The tabs may have either normal data or formulas in various cells. In the case of formulas, the formulas may be nested from one sheet to the next (i.e. a formula on sheet1 refers to a formula on sheet2 which in turn refers to a formula on sheet3, etc.).
I have a hidden tab that contains the following: source sheet, source range, target sheet, and target range.
A named range has been created over these 4 fields and all applicable rows.
When we wish to save data to the database, we loop through every row in the range mapping and copy the data from the source sheet/range to the target sheet/range. After this, the applicable data is serialized into XML and sent to a web service to be saved.
The problem that we wish to resolve is that we want to mark a cell on a hidden sheet when a change is made by the user to a source range. Since formulas can be nested, the Worksheet_Change event does not pick up the change.
Since a change on one sheet may affect another sheet that is not the active sheet, the Workbook_SheetChange event does not catch the change either.
Is there any way form me to catch when a sheet defined in the mapping is changed, even if it is the result of a formula change several levels deep?
Edit
Thank you for your responses. I was attempting to find the fastest and least process intensive way to determine if data changes within a monitored range. The data may consist of actual data or of nested formulas.
My research showed that I could not actually achieve this result by taking range intersections as I could not detect if the data within a monitored range was modified. This is due to the fact that the monitored range may not be on the active sheet and also may contain formulas.
I have shown the method used to actually detect a change below. If there is any feedback on a better way to achieve the same result, I would appreciated it.
Worksheet_Change event will not work if a cell value is changed by a formula, you need Worksheet_Calculate.
Check out my example workbook here.
And Here for the WebPage of example codes
There is no "easy" way to detect if a nested formula has changed when the formula being monitored is not on the active sheet. While my hope was to detect the modified range and use an intersection of ranges to set a flag, this was not possible because the Worksheet_Change event does not work on formulas and the Workbook_SheetChange event only works on the active sheet. Since my workbooks have over 20+ tabs and 20 - 30 ranges being monitored, this approach does not work. This approach was desired for speed purposes.
Instead, the workbook will need to "check" to see if the current values are the same as the last time the save to database event was called. If not, a dirty flag will be set.
The code for this approach is provided below.
An example of the mapping range is shown in the picture below though in practice there are 20-30 rows comprising this range.
There are three other sheets where Sheet3 contains actual data in A1:H1 and Sheet2 has formulas pointing to Sheet3. Sheet1 has formulas pointing to Sheet2.
As the mapping range indicates, we are looking at a range on Sheet1, even though changes may be made to Sheet3.
The code used is as provided below.
Option Explicit
Public Sub DetermineIfEditOccurred()
Dim oMappingRange As Range
Dim szSourceTab As String
Dim szSourceRange As String
Dim oSourceRange As Range
Dim szTargetTab As String
Dim szTargetRange As String
Dim oTargetRange As Range
Dim oWorksheetSource As Worksheet
Dim oWorksheetTarget As Worksheet
Dim oRangeIntersection As Range
Dim nRowCounter As Long
Dim nCellCounter As Long
Dim szSourceValue As String
Dim szTargetValue As String
Dim oCell As Range
Dim bIsDirty As Boolean
If Range(ThisWorkbook.Names("DirtyFlag")).Value = 0 Then
Set oMappingRange = Range(ThisWorkbook.Names("Mapping"))
For nRowCounter = 1 To oMappingRange.Rows.Count
szSourceTab = oMappingRange(nRowCounter, 1)
szSourceRange = oMappingRange(nRowCounter, 2)
szTargetTab = oMappingRange(nRowCounter, 3)
szTargetRange = oMappingRange(nRowCounter, 4)
Set oWorksheetSource = ThisWorkbook.Worksheets(szSourceTab)
Set oWorksheetTarget = ThisWorkbook.Worksheets(szTargetTab)
Set oSourceRange = oWorksheetSource.Range(szSourceRange)
Set oTargetRange = oWorksheetTarget.Range(szTargetRange)
nCellCounter = 1
For Each oCell In oSourceRange.Cells
szSourceValue = oCell.Value
If szSourceValue = "#NULL!" Or _
szSourceValue = "#DIV/0!" Or _
szSourceValue = "#VALUE!" Or _
szSourceValue = "#REF!" Or _
szSourceValue = "#NAME?" Or _
szSourceValue = "#NUM!" Or _
szSourceValue = "#N/A" Then
szSourceValue = ""
End If
szTargetValue = GetCellValueByPosition(oTargetRange, nCellCounter)
If szSourceValue <> szTargetValue Then
Range(ThisWorkbook.Names("DirtyFlag")).Value = 1
bIsDirty = True
Exit For
End If
nCellCounter = nCellCounter + 1
Next
If bIsDirty Then
Exit For
End If
Next
End If
End Sub
Public Function GetCellValueByPosition(oRange As Range, nPosition As Long) As String
Dim oCell As Range
Dim nCounter As Long
Dim szValue As String
nCounter = 1
For Each oCell In oRange
If nCounter = nPosition Then
szValue = oCell.Value
Exit For
End If
nCounter = nCounter + 1
Next
GetCellValueByPosition = szValue
End Function
The Workbook_SheetChange event is as follows:
Option Explicit
Private Sub Workbook_BeforeClose(Cancel As Boolean)
Call DetermineIfEditOccurred
End Sub
Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
If Sh.Name <> "MAPPING" Then
Call DetermineIfEditOccurred
End If
End Sub