Update a cell value with Macro VBA - vba

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

Related

Excel VBA: Trigger macro on cut/paste/delete/insert events

I have a conditional formatting rule defined as macro, which deletes the old rules and replaces them with updates ones:
Sub setCondFormat()
Set Table = ActiveSheet.ListObjects("Rules")
Table.Range.FormatConditions.Delete
Set Attribute = Table.ListColumns("Attribute")
With Attribute.DataBodyRange.FormatConditions _
.Add(xlExpression, xlEqual, "=ISEMPTY(A2)")
With .Interior
.ColorIndex = 0
End With
End With
End Sub
The conditional formatting in Excel needs to be updated. Otherwise the
cell ranges in the rules get fragmented.
Let's say you have two rules:
Make $A$1:$A$30 red
Make $B$1:$B$30 blue Now select A10:B10 and copy/paste that to A20:B20.
What Excel will do is to delete the conditional formatting.
For A20:B20 from the rules that applied to those cells and add new
rules that have the formatting for A20:B20. You end up with four
rules:
Make =$A$20 red
Make =$B$20 blue
Make =$A$1:$A$19,$A$21:$A$30 red
Make =$B$1:$B$19,$B$21:$B$30 blue
This happens, when the table structure gets changed through cut/paste/delete/insert events.
How to trigger the above VBA macro on cut/paste/delete/insert events?
You could use a shortcut for your macro
VBA event trigger on copy?
If you don't want to go this way you'll need to use the Windows API:
Is there any event that fires when keys are pressed when editing a cell?
The solution I found is create a new Sheet with the content of your table when you open the Workbook. First you need to create a Module with the Public Variables.
Public OldRange As Range
Public NewRange As Range
Public Table As ListObject
Then, use the event Open of your Workbook.
Private Sub Workbook_Open()
Dim sh As Worksheet
Dim address As String
For Each sh In Worksheets
If sh.Name = "DATA" Then
Worksheets("DATA").Activate
ActiveSheet.Delete
End If
Next
ActiveWorkbook.Sheets.Add After:=Worksheets(Worksheets.Count)
ActiveSheet.Name = "DATA"
Set sh = ActiveWorkbook.Sheets("Plan1")
sh.Activate
Set Table = ActiveSheet.ListObjects("Rules")
Set OldRange = Table.Range
address = Table.Range.address
Table.Range.Copy
Set sh = ActiveWorkbook.Sheets("DATA")
sh.Activate
Range(address).PasteSpecial (xlPasteAll)
End Sub
And then, use the event Worksheet_Change to verify the content of your original table with the earlier saved table.
Private Sub Worksheet_Change(ByVal Target As Range)
Set Table = ActiveSheet.ListObjects("Rules")
If Intersect(Target, Table.Range) Is Nothing Then Exit Sub 'this will guarantee that the change made in your sheet is in your desired table
Set NewRange = Table.Range
Dim rng As Range
Dim rngaddr As String
Dim TableChanged As Boolean
TableChanged = False
For Each rng In NewRange
rngaddr = rng.address
If rng.Value <> ActiveWorkbook.Sheets("DATA").Range(rngaddr).Value Then
'do something
TableChanged = True
End If
Next
End Sub
Remember: you need to save the content of your table every time you changed it.

Add textbox value to it's destination

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

Listbox in Userform

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

Detect change from nested formulas

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

Create a Hyperlink that searches worksheet and selects cell with duplicate contents

I have a value in a cell. This value is duplicated, intentionally, in another part of the worksheet. I would like to be able to click the cell in C5 with contents 12345 and it selects the cell in A1:1600 that contains the same value. I will never have more than 2 cells with this same value in the worksheet, but the values will change.
I appreciate any help you can offer.
Thank You.
This should do the trick - I was unsure of the range you wanted to specify, so I just put it as A1:Z1600, but change it as necessary.
In VBA, paste this into your sheet's code module:
Private Sub Worksheet_FollowHyperlink(ByVal Target As Hyperlink)
Dim OriginalAddress As String
Dim ValToFind As String
Dim CurrentCell As Range
OriginalAddress = Target.Parent.Address
ValToFind = Target.Parent.Value
With Range("A1:Z1600")
Set CurrentCell = .Find(What:=ValToFind)
If OriginalAddress = CurrentCell.Address Then
.FindNext(After:=CurrentCell).Activate
Else
CurrentCell.Activate
End If
End With
End Sub
You can use the Hyperlink function to do what you wanting. But you would have to manually type out the formula for each cell that you wanted to link... Here's an example:
=HYPERLINK("[Book1]Sheet1!F2",12345)
This method is very unwieldy. The only way to do what you want in a robust fashion would be to use VBA.
Edit: I was able to duplicate the issue. The below edits seem to resolve the issue.
This VBA solution used the FindNext function to find the next value in the sheet:
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
Dim FirstAddress As String
Dim Rng As Range
Dim x As Long
x = Me.UsedRange.Rows.Count
FirstAddress = Target.Address
Set Rng = Me.UsedRange.Find(Target.Value)
If FirstAddress = Rng.Address Then
Me.UsedRange.FindNext(Rng).Select
Else
Rng.Select
End If
End Sub
This works with a double click for the sheet the code is in, and it doesn't matter where the duplicate value is in that sheet. Just place the code in your worksheet's module.
One last way to do this (although still inferior to VBA) is to insert the hyperlink:
In this example, you click on A2>go to Insert Tab>Hyperlink>Place in This Document and enter the corresponding cell. This hyperlinks cell A2 to F2 so that when A2 is selected F2 is selected.