vba commandbutton calling an worksheet update

BobtBuilder

New Member
Joined
Sep 1, 2023
Messages
44
Office Version
  1. 365
Platform
  1. Windows
I have a worksheet update that simply takes a line resorts it and then brings you to the line that was entered.
The problem is I have a command button that adds lines based on an action, so it calls the worksheet update but the code that takes me to the line should not be run if a commandbutton is used just the code that resorts.
So I was wondering if there was a way to identify that the code was activated from a commandbutton, tried a variable but it gets deinitialised when leaving the commandbutton.

Not sure if this is clear

Thanks
 

Excel Facts

When they said...
When they said you are going to "Excel at life", they meant you "will be doing Excel your whole life".
You should not have Command Buttons calling Worksheet update event procedure code.
Event procedure code is meant to be called automatically upon some action (like the updating of a cell).

If both are to be doing the same thing, it is probably better to make a non-event procedure code that BOTH your command button AND your event procedure can call.
 
Upvote 0
You should not have Command Buttons calling Worksheet update event procedure code.
Event procedure code is meant to be called automatically upon some action (like the updating of a cell).

If both are to be doing the same thing, it is probably better to make a non-event procedure code that BOTH your command button AND your event procedure can call.
I did not know it was calling it until i got an error. but since I am updating a table it calls that procedure, not sure how to alter it
 
Upvote 0
Can you post your code, and same data samples, and work us through an example of what is happening and what should happen?
 
Upvote 0
I have been trying to load some data and the vba code, but cant seem to do it. My network admin will not allow us to add xl2bb
 
Upvote 0
At least post your VBA code (nothing special needed to do that, see here: How to Post Your VBA Code), and a screen print of your data.
Here is the code, sorry I had no access to the sheet.
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
If Target.Cells.CountLarge > 1 Then Exit Sub
If Target.Row > 1 And Target.Column = 10 Then
If Target.Formula = "" Then
Target.Formula = Target.Offset(-1, 0).Formula
End If
End If
End Sub
Private Sub Worksheet_Change(ByVal Target As Range)

Dim rngIntersect As Range
Dim tbl As ListObject
Set tbl = Me.ListObjects(1) ' Assuming your table is the first ListObject on the sheet
Set rngIntersect = Intersect(Target, tbl.ListColumns("Date").DataBodyRange)

' Check if the changed cell is within the table
If Not rngIntersect Is Nothing Then
' Disable events to prevent recursive triggering
Application.EnableEvents = False
Application.ScreenUpdating = False

' Set up and apply search characteristic to the 1st selected cell in the Date column
Dim origFnt As String, tmpFnt As String
With rngIntersect.Cells(1)
origFnt = .Font.Name
tmpFnt = "Comic Sans MS"
.Font.Name = tmpFnt
End With

' Sort the table based on the "Date" column in ascending order
tbl.Sort.SortFields.Clear
tbl.Sort.SortFields.Add Key:=tbl.ListColumns("Date").DataBodyRange, SortOn:=xlSortOnValues, Order:=xlAscending
tbl.Sort.Apply

' Find search characteristic applied to Target cell
With Application.FindFormat
.Clear
.Font.Name = tmpFnt
End With

Dim origCell As Range
With tbl.ListColumns("Date").DataBodyRange
Set origCell = .Find(What:="*", SearchFormat:=True)
.Font.Name = origFnt ' Apply to whole column or table might get confused
End With
Application.FindFormat.Clear

' Activate original target cell, if multiple cells 1st cell in date column in target range
'If ActiveSheet.Shapes("CommandButton1").OLEFormat.Object.Object Is Me.CommandButton1 Then
' Code to execute when CommandButton1 is clicked
' MsgBox "CommandButton1 was clicked!"
'Else
' Code to execute when CommandButton1 is not clicked
' origCell.Select
'End If

' If runOrigCellSelect <> 1 Then
origCell.Select
' End If



' Re-enable events
Application.EnableEvents = True
Application.ScreenUpdating = True

End If
End Sub
Private Sub CommandButton1_Click()
' Sub ModifyDateWithNumericValue()
Dim userMonth As Integer
Dim userDay As Integer
Dim modifiedDate As Date
Dim userInput As Variant
Dim cellChangeCount As Long

Dim wsName As String
Dim targetCell As Range

' Set the target cell (N3 in this case) for the active sheet
Set targetCell = ActiveSheet.Range("N3")

' Get the value from the target cell
wsName = targetCell.Value

' Check if the worksheet with the specified name exists
On Error Resume Next

' Initialize the cell change count
cellChangeCount = 0

' Prompt the user for the month using a MsgBox
userInput = InputBox("Enter the month (1-12):")

' Check if the user provided a valid numeric value for the month
If IsNumeric(userInput) Then
userMonth = CInt(userInput)

' Check if the month is within the valid range (1-12)
If userMonth >= 1 And userMonth <= 12 Then
' Declare a cell variable to keep track of the current cell
Dim currentCell As Range
Set currentCell = ThisWorkbook.Sheets(wsName).Range("M20") ' Change the sheet and starting cell as needed

' Initialize the userDay variable
userDay = CInt(ThisWorkbook.Sheets(wsName).Range("L20").Value)

' Loop until the current cell is empty
Do While currentCell.Value <> ""
' Create a new date using the provided month and day
modifiedDate = DateSerial(Year(Date), userMonth, userDay)

' Copy the value of the modified date to the current cell
currentCell.Value = modifiedDate

' Increment the cell change count
cellChangeCount = cellChangeCount + 1

' Move to the next cell (one cell down)
Set currentCell = currentCell.Offset(1, 0)

' Offset the userDay value as well (one cell down)
userDay = CInt(currentCell.Offset(0, -1).Value)
Loop

Dim sourceRange As Range
Dim destRange As Range
Dim lastRow As Long
Dim lastCol As Long
Dim ws As Worksheet
Dim targetRow As ListRow
Dim targetTable As ListObject
Dim sourceRow As Range
Dim runOrigCellSelect As Long

' Set the source worksheet
Set ws = ThisWorkbook.Sheets(wsName) ' Change "Sheet1" to your source sheet name

' Define the source range (adjust the starting cell as needed)
Set sourceRange = ws.Range("M20:V40") ' Change "A1" to the starting cell of your source data

' Set the target table where you want to paste the data
Set targetTable = ws.ListObjects(wsName) ' Change "Table1" to your table name

' Find the last row and last column with data in the source range
lastRow = ws.Cells(ws.Rows.Count, sourceRange.Column).End(xlUp).Row
lastCol = ws.Cells(sourceRange.Row, ws.Columns.Count).End(xlToLeft).Column

' Loop through each row in the source range
For Each sourceRow In sourceRange.Rows
' Check if the row has data in it
If WorksheetFunction.CountA(sourceRow) > 0 Then

runOrigCellSelect = 1

' Set the last cell in the source row
Set lastCell = sourceRow.Cells(1, lastCol)

' Add a new row to the target table
Set targetRow = targetTable.ListRows.Add
' Copy the source row and paste it into the target row
sourceRow.Copy
targetRow.Range.Cells(1, 1).PasteSpecial xlPasteFormulas ' You can change the paste type as needed
' Clear the clipboard (optional)
Application.CutCopyMode = False
End If
Next sourceRow

' Clean up
Set sourceRange = Nothing
Set targetTable = Nothing
Set targetRow = Nothing
Set ws = Nothing
runOrigCellSelect = 0

Else
MsgBox "Invalid month. Please enter a month between 1 and 12."
End If
Else
MsgBox "Invalid input. Please enter a numeric value for the month."
End If
End Sub
Private Sub CommandButton2_Click()

Dim ws As Worksheet
Dim userMonth As Integer
Dim userDay As Integer
Dim modifiedDate As Date
Dim cellChangeCount As Long
Dim wsName As String
Dim currentCell As Range
Dim dayCell As Range
Dim sourceRange As Range
Dim destRange As Range
Dim lastRow As Long
Dim lastCol As Long
Dim targetRow As ListRow
Dim targetTable As ListObject
Dim sourceRow As Range

runOrigCellSelect = 1

' Set the target worksheet (specified in cell N3 of the active sheet)
wsName = ActiveSheet.Range("N3").Value
Set ws = ThisWorkbook.Sheets(wsName)

' Initialize the cell change count
cellChangeCount = 0

' Prompt the user for the month using a MsgBox
' userInput =
strIn = UCase$(InputBox("Bi Weekly Continue Y/N"))

' Check if the month is within the valid range (y/N)
If strIn = "Y" Then
' Loop through the cells in column S and corresponding cells in column R
' Loop until the current cell is empty
Do While currentCell.Value <> ""
For Each currentCell In ws.Range("M45:M" & ws.Cells(ws.Rows.Count, "M").End(xlUp).Row)
Set dayCell = currentCell.Offset(0, -1) ' Corresponding cell in column R
userDay = Day(currentCell.Offset(0, -1)) ' Extract the day from the new date

' Calculate the starting date based on user-provided month and the new day
modifiedDate = dayCell

' Update the date every two weeks in column S
modifiedDate = modifiedDate + 14 ' Add 14 days (two weeks)
currentCell.Value = modifiedDate

' Update the day in column R with the new day
dayCell.Value = currentCell.Value

cellChangeCount = cellChangeCount + 1
'Next currentCell

' Set the source worksheet
Set ws = ThisWorkbook.Sheets(wsName) ' Change "Sheet1" to your source sheet name

' Define the source range (adjust the starting cell as needed)
Set sourceRange = ws.Range("M45:U60") ' Change "A1" to the starting cell of your source data

' Set the target table where you want to paste the data
Set targetTable = ws.ListObjects(wsName) ' Change "Table1" to your table name

' Find the last row and last column with data in the source range
lastRow = ws.Cells(ws.Rows.Count, sourceRange.Column).End(xlUp).Row
lastCol = ws.Cells(sourceRange.Row, ws.Columns.Count).End(xlToLeft).Column

' Loop through each row in the source range
For Each sourceRow In sourceRange.Rows
' Check if the row has data in it
If WorksheetFunction.CountA(sourceRow) > 0 Then

' Set the last cell in the source row
Set lastCell = sourceRow.Cells(1, lastCol)

' Add a new row to the target table
Set targetRow = targetTable.ListRows.Add
' Copy the source row and paste it into the target row
sourceRow.Copy
targetRow.Range.Cells(1, 1).PasteSpecial xlPasteFormulas ' You can change the paste type as needed
' Clear the clipboard (optional)
Application.CutCopyMode = False
End If
Next sourceRow

' Clean up
Set sourceRange = Nothing
Set targetTable = Nothing
Set targetRow = Nothing
Set ws = Nothing

End If

End Sub
 
Upvote 0
You did not follow the instructions for posting code (using the Code tags, as shown in the link I provided), nor did you post any samples of your sheets (even if you cannot use the add-in, you CAN at least take a screen print of your data and post the image here so we have some idea of how your data is structured).

Alternatively, you could post your file to a file sharing site and provide a link to it, so we can download it directly.
If you do that, just be sure to remove any sensitive data first.
 
Upvote 0
Ok So here goes again, sorry about the code, its just that it is all vba so did not see the need

So again when i hit commandbutton1, it adds rows to the table, because it adds rows it calls the add row vba script, and there are things like reformatting the text and then finding the text that is not necessary when I run both the command buttons, just when I add a single row,

VBA Code:
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
If Target.Cells.CountLarge > 1 Then Exit Sub
If Target.Row > 1 And Target.Column = 10 Then
If Target.Formula = "" Then
Target.Formula = Target.Offset(-1, 0).Formula
End If
End If
End Sub

VBA Code:
Private Sub Worksheet_Change(ByVal Target As Range)

Dim rngIntersect As Range
Dim tbl As ListObject
Set tbl = Me.ListObjects(1) ' Assuming your table is the first ListObject on the sheet
Set rngIntersect = Intersect(Target, tbl.ListColumns("Date").DataBodyRange)

' Check if the changed cell is within the table
If Not rngIntersect Is Nothing Then
' Disable events to prevent recursive triggering
Application.EnableEvents = False
Application.ScreenUpdating = False

' Set up and apply search characteristic to the 1st selected cell in the Date column
Dim origFnt As String, tmpFnt As String
With rngIntersect.Cells(1)
origFnt = .Font.Name
tmpFnt = "Comic Sans MS"
.Font.Name = tmpFnt
End With

' Sort the table based on the "Date" column in ascending order
tbl.Sort.SortFields.Clear
tbl.Sort.SortFields.Add Key:=tbl.ListColumns("Date").DataBodyRange, SortOn:=xlSortOnValues, Order:=xlAscending
tbl.Sort.Apply

' Find search characteristic applied to Target cell
With Application.FindFormat
.Clear
.Font.Name = tmpFnt
End With

Dim origCell As Range
With tbl.ListColumns("Date").DataBodyRange
Set origCell = .Find(What:="*", SearchFormat:=True)
.Font.Name = origFnt ' Apply to whole column or table might get confused
End With
Application.FindFormat.Clear

' Activate original target cell, if multiple cells 1st cell in date column in target range
'If ActiveSheet.Shapes("CommandButton1").OLEFormat.Object.Object Is Me.CommandButton1 Then
' Code to execute when CommandButton1 is clicked
' MsgBox "CommandButton1 was clicked!"
'Else
' Code to execute when CommandButton1 is not clicked
' origCell.Select
'End If

' If runOrigCellSelect <> 1 Then
origCell.Select
' End If



' Re-enable events
Application.EnableEvents = True
Application.ScreenUpdating = True

End If
End Sub

VBA Code:
Private Sub CommandButton1_Click()
' Sub ModifyDateWithNumericValue()
Dim userMonth As Integer
Dim userDay As Integer
Dim modifiedDate As Date
Dim userInput As Variant
Dim cellChangeCount As Long

Dim wsName As String
Dim targetCell As Range

' Set the target cell (N3 in this case) for the active sheet
Set targetCell = ActiveSheet.Range("N3")

' Get the value from the target cell
wsName = targetCell.Value

' Check if the worksheet with the specified name exists
On Error Resume Next

' Initialize the cell change count
cellChangeCount = 0

' Prompt the user for the month using a MsgBox
userInput = InputBox("Enter the month (1-12):")

' Check if the user provided a valid numeric value for the month
If IsNumeric(userInput) Then
userMonth = CInt(userInput)

' Check if the month is within the valid range (1-12)
If userMonth >= 1 And userMonth <= 12 Then
' Declare a cell variable to keep track of the current cell
Dim currentCell As Range
Set currentCell = ThisWorkbook.Sheets(wsName).Range("M20") ' Change the sheet and starting cell as needed

' Initialize the userDay variable
userDay = CInt(ThisWorkbook.Sheets(wsName).Range("L20").Value)

' Loop until the current cell is empty
Do While currentCell.Value <> ""
' Create a new date using the provided month and day
modifiedDate = DateSerial(Year(Date), userMonth, userDay)

' Copy the value of the modified date to the current cell
currentCell.Value = modifiedDate

' Increment the cell change count
cellChangeCount = cellChangeCount + 1

' Move to the next cell (one cell down)
Set currentCell = currentCell.Offset(1, 0)

' Offset the userDay value as well (one cell down)
userDay = CInt(currentCell.Offset(0, -1).Value)
Loop

Dim sourceRange As Range
Dim destRange As Range
Dim lastRow As Long
Dim lastCol As Long
Dim ws As Worksheet
Dim targetRow As ListRow
Dim targetTable As ListObject
Dim sourceRow As Range
Dim runOrigCellSelect As Long

' Set the source worksheet
Set ws = ThisWorkbook.Sheets(wsName) ' Change "Sheet1" to your source sheet name

' Define the source range (adjust the starting cell as needed)
Set sourceRange = ws.Range("M20:V40") ' Change "A1" to the starting cell of your source data

' Set the target table where you want to paste the data
Set targetTable = ws.ListObjects(wsName) ' Change "Table1" to your table name

' Find the last row and last column with data in the source range
lastRow = ws.Cells(ws.Rows.Count, sourceRange.Column).End(xlUp).Row
lastCol = ws.Cells(sourceRange.Row, ws.Columns.Count).End(xlToLeft).Column

' Loop through each row in the source range
For Each sourceRow In sourceRange.Rows
' Check if the row has data in it
If WorksheetFunction.CountA(sourceRow) > 0 Then

runOrigCellSelect = 1

' Set the last cell in the source row
Set lastCell = sourceRow.Cells(1, lastCol)

' Add a new row to the target table
Set targetRow = targetTable.ListRows.Add
' Copy the source row and paste it into the target row
sourceRow.Copy
targetRow.Range.Cells(1, 1).PasteSpecial xlPasteFormulas ' You can change the paste type as needed
' Clear the clipboard (optional)
Application.CutCopyMode = False
End If
Next sourceRow

' Clean up
Set sourceRange = Nothing
Set targetTable = Nothing
Set targetRow = Nothing
Set ws = Nothing
runOrigCellSelect = 0

Else
MsgBox "Invalid month. Please enter a month between 1 and 12."
End If
Else
MsgBox "Invalid input. Please enter a numeric value for the month."
End If
End Sub

VBA Code:
Private Sub CommandButton2_Click()

Dim ws As Worksheet
Dim userMonth As Integer
Dim userDay As Integer
Dim modifiedDate As Date
Dim cellChangeCount As Long
Dim wsName As String
Dim currentCell As Range
Dim dayCell As Range
Dim sourceRange As Range
Dim destRange As Range
Dim lastRow As Long
Dim lastCol As Long
Dim targetRow As ListRow
Dim targetTable As ListObject
Dim sourceRow As Range

runOrigCellSelect = 1

' Set the target worksheet (specified in cell N3 of the active sheet)
wsName = ActiveSheet.Range("N3").Value
Set ws = ThisWorkbook.Sheets(wsName)

' Initialize the cell change count
cellChangeCount = 0

' Prompt the user for the month using a MsgBox
' userInput =
strIn = UCase$(InputBox("Bi Weekly Continue Y/N"))

' Check if the month is within the valid range (y/N)
If strIn = "Y" Then
' Loop through the cells in column S and corresponding cells in column R
' Loop until the current cell is empty
Do While currentCell.Value <> ""
For Each currentCell In ws.Range("M45:M" & ws.Cells(ws.Rows.Count, "M").End(xlUp).Row)
Set dayCell = currentCell.Offset(0, -1) ' Corresponding cell in column R
userDay = Day(currentCell.Offset(0, -1)) ' Extract the day from the new date

' Calculate the starting date based on user-provided month and the new day
modifiedDate = dayCell

' Update the date every two weeks in column S
modifiedDate = modifiedDate + 14 ' Add 14 days (two weeks)
currentCell.Value = modifiedDate

' Update the day in column R with the new day
dayCell.Value = currentCell.Value

cellChangeCount = cellChangeCount + 1
'Next currentCell

' Set the source worksheet
Set ws = ThisWorkbook.Sheets(wsName) ' Change "Sheet1" to your source sheet name

' Define the source range (adjust the starting cell as needed)
Set sourceRange = ws.Range("M45:U60") ' Change "A1" to the starting cell of your source data

' Set the target table where you want to paste the data
Set targetTable = ws.ListObjects(wsName) ' Change "Table1" to your table name

' Find the last row and last column with data in the source range
lastRow = ws.Cells(ws.Rows.Count, sourceRange.Column).End(xlUp).Row
lastCol = ws.Cells(sourceRange.Row, ws.Columns.Count).End(xlToLeft).Column

' Loop through each row in the source range
For Each sourceRow In sourceRange.Rows
' Check if the row has data in it
If WorksheetFunction.CountA(sourceRow) > 0 Then

' Set the last cell in the source row
Set lastCell = sourceRow.Cells(1, lastCol)

' Add a new row to the target table
Set targetRow = targetTable.ListRows.Add
' Copy the source row and paste it into the target row
sourceRow.Copy
targetRow.Range.Cells(1, 1).PasteSpecial xlPasteFormulas ' You can change the paste type as needed
' Clear the clipboard (optional)
Application.CutCopyMode = False
End If
Next sourceRow

' Clean up
Set sourceRange = Nothing
Set targetTable = Nothing
Set targetRow = Nothing
Set ws = Nothing

End If

End Sub
 

Attachments

  • excel.png
    excel.png
    113.9 KB · Views: 3
Upvote 0

Forum statistics

Threads
1,215,069
Messages
6,122,959
Members
449,096
Latest member
Anshu121

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top