I have an excel workbook with modeless form. The way it's setup is that: each sheet in the workbook has a tab in the form. Each field in these tabs is Linked to a cell in corresponding sheet. So when a value is changed/updated in the form, it is automatically updated in the relevant cell. The way I am doing this is by using the onChange event for each filed which call's a UDF that does the updating. My question, there are a lot of fields in the form and lots more to be added. Is there a way to update relevant cell when a field in the form is selected without having to add the call to a UDF in onChange event for each field?
I have tried using things like ControlSource but that only one way where it just updates the value in the form but doesn't update the value in the cell when form is updated.
As a side note, unfortunately I cannot share the form or the sheet but am willing to answer any questions
EDIT
Below is the function that updates the field:
Sub UpdateWorksheetValue(ByVal oObj As Object)
Dim oWS As Worksheet
Dim sCurrentValue As String
Dim iC As Long
' Lets check if tag is set
If Len(Trim(oObj.Tag)) = 0 Then
MsgBox "Empty tag found for '" & oObj.Name & "' field. Failed to update field value" & vbCrLf & vbCrLf & "Please contact system administrator with this information", vbCritical + vbOKOnly, "Update Failed"
Exit Sub
ElseIf Len(Trim(Mid(oObj.Tag, InStr(1, oObj.Tag, "¬") + 1))) = 0 Then
MsgBox "Tag for '" & oObj.Name & "' field does not include page title. Failed to update field value" & vbCrLf & vbCrLf & "Please contact system administrator with this information", vbCritical + vbOKOnly, "Update Failed"
Exit Sub
End If
' Set worksheet
Select Case LCase(Trim(Mid(oObj.Tag, InStr(1, oObj.Tag, "¬") + 1)))
Case "client identification"
Set oWS = oWB.Worksheets("Client Identification - Output")
Case "request details"
Set oWS = oWB.Worksheets("Request Details - Output")
Case "db responsible individuals"
Set oWS = oWB.Worksheets("DB Responsible Ind - Output")
Case "additional details"
Set oWS = oWB.Worksheets("Additional Details - Output")
End Select
' Set value
With oWS
' Lets check if tag is set
If Len(Trim(Mid(oObj.Tag, 1, InStr(1, oObj.Tag, "¬") - 1))) = 0 Then
MsgBox "Tag for '" & oObj.Name & "' field does not include corresponding cell information. Failed to update field value in '" & oWS.Name & "' worksheet" & vbCrLf & vbCrLf & "Please contact system administrator with this information", vbCritical + vbOKOnly, "Update Failed"
Exit Sub
End If
' Set the search value
.Range("Z1").Value = Mid(oObj.Tag, 1, InStr(1, oObj.Tag, "¬") - 1)
DoEvents
' If a row with tag text is not found, throw a message and exit sub
If Len(Trim(.Range("Z2").Value)) = 0 Then
MsgBox "Unable to find corresponding cell for '" & oObj.Name & "' field in '" & .Name & "' worksheet. Failed to update field value" & vbCrLf & vbCrLf & "Please ensure that the field's 'Tag' matches a cell in the sheet or contact system administrator", vbCritical + vbOKOnly, "Update Failed"
Exit Sub
End If
' Set field value
Select Case LCase(TypeName(oObj))
Case "textbox", "combobox"
.Range("B" & .Range("Z2").Value).Value = oObj.Value
Case "optionbutton"
If oObj.Value = True Then
.Range("B" & .Range("Z2").Value).Value = oObj.Caption
Else
.Range("B" & .Range("Z2").Value).Value = ""
End If
Case "listbox"
' First lets the current cell value
sCurrentValue = .Range("B" & .Range("Z2").Value).Value
' Now lets build the string for the cell
For iC = 0 To oObj.ListCount - 1
If oObj.Selected(iC) And InStr(1, sCurrentValue, oObj.List(iC)) = 0 Then
sCurrentValue = sCurrentValue & "/" & oObj.List(iC)
ElseIf Not oObj.Selected(iC) And InStr(1, sCurrentValue, oObj.List(iC)) > 0 Then
sCurrentValue = Replace(sCurrentValue, "/" & oObj.List(iC), "")
End If
Next
' And finally, set the value
.Range("B" & .Range("Z2").Value).Value = sCurrentValue
End Select
End With
' Clear object
Set oWS = Nothing
End Sub
EDIT 2
I now have a class called formEventClass as suggested by David. Contents of the class are:
Option Explicit
Public WithEvents tb As MSForms.TextBox
Private Sub tb_Change()
UpdateWorksheetValue (tb)
End Sub
But when I make a change in any given text box, cells are not updated (as per David's suggestion, I've removed the call to UpdateWorksheetValue in text box onChange event. Cells are not updated even when I tab out of the field. As this is working for David, I suspect I am missing something here
If you want to get fancy using WithEvents...
Create a Class Module and name it tbEventClass. Put the following code in this module.
Option Explicit
Public WithEvents tb As MSForms.TextBox
Private Sub tb_Change()
Call UpdateWorksheetValue(tb)
End Sub
This defines a custom class (tbEventClass) which is responsive to the events of it's tb property which is a TextBox. You'll need to map your textboxes to instances of this class during the form's Initialize event:
Public textbox_handler As New Collection
Private Sub UserForm_Initialize()
Dim ctrl As Control, tbEvent As tbEventClass
For Each ctrl In Me.Controls
If TypeName(ctrl) = "TextBox" Then
Set tbEvent = New tbEventClass
Set tbEvent.tb = ctrl
textbox_handler.Add tb
End If
Next
End Sub
Important: You will either need to remove or modify the Change event handlers in the UserForm module to avoid duplicate calls to the "update" procedure. If the only thing going on in those event handlers is the call to your update macro, just get remove the event handlers entirely, they're fully represented by the tbClass. If those events contain other code that does other stuff, just remove or comment out the line(s) that call on your update function.
Update:
This is working for me with the controls within a MultiPage and required ZERO changes to the implemented code above.
Related
Once every 3 months we make a file available for our engineers.
This Excel files, pulls data from an Access file and shows it in Excel format.
Since some of this data doesn't change, we don't know whether the engineers haven't looked at it or whether the value isn't changed. What i'm trying to implement is some sort of "confirmation" button so we know the value shown is actually confirmed.
What i'm trying to do is enter an extra column in our access file called "confirmation".
When we pull this data in our excel file, i'm trying to find a way to convert that "confirmation field" into a commandbutton so whenever the data gets pulled, a commandbutton shows up on every line. Whenever the button gets clicked, the data gets saved in our Access file so we know the line is actually confirmed.
Maybe there are some other , easier, ways to do this?
I currently have some code to save excel data in Access but its not working in its current form:
Sub S_SaveDataToDB()
If ActiveSheet.Name = "Estimate" Then
ViKey = 1
Else
ViKey = 2
End If
For i = 1 To ActiveSheet.ListObjects("TB_ACC" & ViKey).ListRows.Count
VsData = "SET [BE] = '" & F_FilterData(ActiveSheet.Cells(7 + i, 17)) & "', [PO STATUS] = '" & F_FilterData(ActiveSheet.Cells(7 + i, 18)) & "', [REMARKS] = '" & F_FilterData(ActiveSheet.Cells(7 + i, 19)) & "', [LOGDATE] = '" & Now() & "', [LOGID] = '" & Environ("Username") & "' WHERE [PO item] = '" & ActiveSheet.Cells(7 + i, 9) & "'"
If Len(F_FilterData(ActiveSheet.Cells(7 + i, 16))) + Len(F_FilterData(ActiveSheet.Cells(7 + i, 17))) + Len(F_FilterData(ActiveSheet.Cells(7 + i, 18))) > 0 Then Call S_UpdateDataInDB(VsData)
Next i
MsgBox "Data has been saved"
and
Sub S_UpdateDataInDB(VsData)
Dim cnDB As New ADODB.Connection
VsDBPath = ThisWorkbook.Sheets("Settings").Range("B2").Value
VsTable = "KCD"
cnDB.Open "Provider=Microsoft.ACE.OLEDB.12.0;" & "Data Source=" & VsDBPath & ";" & "Jet OLEDB:Engine Type=5;" & "Persist Security Info=False;"
cnDB.Execute ("UPDATE " & VsTable & " " & VsData)
cnDB.Close
End Sub
Differences here are:
I want to just save text ("Data confirmed") for that particular cell.
So if one wants to confirm data on Row 8 and clicks "Data confirm". It should only save "Data confirm" for row 8 in access.
Generally, when I'm trying to add a feature to every row in a column, I'll use a hyperlink. It fits neatly into the cell, it can be anchored to a specific cell, and it also shows when it's been followed (the color changes). I've mocked together some code as an example; try to adapt it to your application and let me know if you need help.
First, in a standard module, enter the following code to create the hyperlinks. Presumably, you'd embed this into the code that pulls the data.
Sub PullData()
Dim sh As Worksheet
Dim lastRow As Long
'Pull the data
' DO STUFF
'Identify the range of the pulled data
Set sh = Sheets("PulledData")
lastRow = sh.Range("A" & sh.Rows.Count).End(xlUp).Row
'Loop from row 2 through last row
For i = 2 To lastRow
'Assuming the 'save' option is in Column c
sh.Cells(i, "C").Hyperlinks.Add Anchor:=sh.Cells(i, "C"), Address:="", _
SubAddress:="", TextToDisplay:="Click To Save"
Next i
End Sub
Next, in the worksheet code for the sheet with the data, enter the below code. This tells the application what to do when a hyperlink is clicked. I created a fake function that is meant to mimic saving the data. You can change this as needed, or use a different design if it suits your needs better.
Private Sub Worksheet_FollowHyperlink(ByVal Target As Hyperlink)
'Confirm that this is a hyperlink in column 3
If Not Intersect(Target.Range, Columns(3)) Is Nothing Then
MsgBox SaveData(Target.Range)
End If
End Sub
Private Function SaveData(rng As Range) As Boolean
Debug.Print rng.Address & " has been saved."
SaveData = True
End Function
I have a userform where you have to enter data into textboxes and then press a button to put the data into the sheet. When I'm typing into the last textbox and I'm done, I click the button and it doesn't respond. Also, I have noticed that my cursor keeps blinking inside the last textbox so I guess there's a problem there (while focused not able to click a button)?
In total I have 4 textboxes, 3 of them use data validation after their value has been updated. The last one does not have data validation.
The weird thing is that, next to the "next button", I have a button to clear the fields and that one works just fine. Below an image from my userform with a little bit of explanation because it's in another language (Dutch). Can anyone help me? Thanks!
The code used for the "next" button is:
Note: the data gets validated not only when they updated the value of the textbox, but also an extra time when they click the next button.
Private Sub AddNextBtn_Click()
AddValueMod.AddDisplayOverview
End Sub
Sub AddDisplayOverview() 'This sub is in the "AddValueMod" module
'Check if information is valid via a function
If AddInformationValid("AccountSelector", True) And AddInformationValid("Date", True) And AddInformationValid("Amount", True) And AddInformationValid("Description", True) Then
'If valid, retrieve entered values
Dim account, dDate, amount, description As String
account = main.AddAccountSelector.Value
dDate = main.AddDateInput.Value
amount = main.AddValue.Value
description = main.AddDescription.Value
'Ask for sheet-writing-confirmation
overview = MsgBox("Kloppen volgende gegevens (kijk goed na!)?" & vbCrLf & vbCrLf & "Rekening: " & account & vbCrLf & "Datum: " & dDate & vbCrLf & "Bedrag: " & amount & vbCrLf & "Beschrijving: " & description & vbCrLf & "Vermeerdering/vermindering: Waarde wordt vermeerderd", vbYesNo + vbQuestion, "Kloppen volgende gegevens?")
If overview = vbYes Then
'Write data to sheet
AddValueMod.AddEnterDataIntoSheet
End If
End If
End Sub
And for the "clear fields" button:
Private Sub AddClearFieldsBtn_Click()
AddValueMod.AddClearFields (True)
End Sub
Sub AddClearFields(askForConfirmation As Boolean) 'This sub is in the "AddValueMod" module
grey = RGB(128, 128, 128)
'If askForConfirmation = True, ask for confirmation before clearing fields
If askForConfirmation = True Then
confirmationMessage = MsgBox("Bent u zeker dat u de velden wilt leegmaken?" + vbCrLf + "U zal terug opnieuw moeten beginnen.", vbYesNo + vbQuestion, "Velden leegmaken?")
If confirmationMessage = vbYes Then
'Clear fields
main.AddAccountSelector.Value = ""
main.AddDateInput.Value = ""
main.AddValue.Value = ""
main.AddDescription.Value = ""
End If
ElseIf askForConfirmation = False Then
'Clear fields
main.AddAccountSelector.Value = ""
main.AddDateInput.Value = ""
main.AddValue.Value = ""
main.AddDescription.Value = ""
End If
'Reset the textboxes' borders (they change if an input error occurred)
main.AddAccountSelectorError.Visible = False
main.AddAccountSelector.BorderStyle = fmBorderStyleSingle
main.AddAccountSelector.BorderColor = grey
main.AddDateInputError.Visible = False
main.AddDateInput.BorderStyle = fmBorderStyleSingle
main.AddDateInput.BorderColor = grey
main.AddValueError.Visible = False
main.AddValue.BorderStyle = fmBorderStyleSingle
main.AddValue.BorderColor = grey
main.AddDescriptionError.Visible = False
main.AddDescription.BorderStyle = fmBorderStyleSingle
main.AddDescription.BorderColor = grey
End Sub
P.S.: I've already tried a possible solution with IsCancel = True/False that I found online in this article. It's possible it didn't work because the article is not quite related to my problem but I felt like I should mention it :).
You did not provide all relevant code. AddInformationValid() and AddEnterDataIntoSheet are missing.
However, if the AddInformationValid() returns False on any item, the behaviour is just as you describe. In AddDisplayOverview() there will be no error message, the AddEnterDataIntoSheet sub will be bypassed and on return from the button handler the cursor remains flashing in the last entry field.
You need to verify and correct the AddInformationValid() Function.
I also strongly recommend to show an error message if the data validation fails.
I have a value (variant) strCompany in my workbook. I would like to determine if this value exists in column A of another workbook, tmp_workbook. If it does not exist there should be a message box. Does the following code make sense (I define the variables tmp_workbook and strCompany earlier in my code)? If not perhaps you can suggest a better way?
On Error GoTo ErrorHandler
Set value_exists_in_table = tmp_workbook.ActiveSheet.Range("A1:A100000").Find(strCompany)
ErrorHandler:
Select Case Err.Number
Case 9, 91
MsgBox "The company " & strCompany & " was not found."
Exit Sub
End Select
The Range.Find method inherits many parameters from the last time it was used; commonly by the user on the worksheet. You should explicitly specify several more commonly used parameters like LookAt:xlWhole or LookAt:xlPart and LookIn:=xlValues or LookIn:=xlFormulas.
I typically stay away from .Find for exact matches in a single row or column. The Excel Application object's native MATCH function does an excellent job of locating a value.
dim rw as variant
with worksheets("Sheet1")
rw = application.match(strCompany, .Columns(1), 0)
if not iserror(rw) then
value_exists_in_table = .cells(rw, 1).value
debug.print value_exists_in_table & " found in row " & rw
else
debug.print "The company " & strCompany & " was not found."
end if
end with
I know that it is possible to use If statement but out of curiosity, as mentioned in the title, is it possible to use SELECT statement to do something as BOLDED below? I've submitted my whole Sub as below for better understanding:
Sub addNewCust_Click()
Dim response As String
response = Application.InputBox(prompt:="", Title:="New customer name", Type:=2)
Select Case response
Case False
Exit Sub
'Check if response is not an empty value AND record found in "CustomerList"
Case Is <> "" & WorksheetFunction.CountIf(Worksheets("CustomerList").Range("B:B"), response) > 0
MsgBox "'" & response & "' already exists on this sheet."
Call addNewCust_Click
'Check if response is not an empty value and record is not found in "Customerlist"
Case Is <> "" & WorksheetFunction.CountIf(Worksheets("CustomerList").Range("B:B"), response) < 1
Sheets("CustomerList").Range("B1048576").End(xlUp).Offset(1, 0).Value = response
MsgBox "'" & response & "' successfully entered!"**
Case Else
MsgBox "Field is empty!"
Call addNewCust_Click
End Select
End Sub
Like this?
Sub addNewCust_Click()
Dim response As String
response = Application.InputBox(prompt:="", Title:="New customer name", Type:=2)
Select Case response
Case False: Exit Sub
'Check if response is not an empty value AND record found in "CustomerList"
Case Is <> ""
If WorksheetFunction.CountIf(Worksheets("CustomerList").Range("B:B"), response) > 0 Then
MsgBox "'" & response & "' already exists on this sheet."
Call addNewCust_Click
Else
Sheets("CustomerList").Range("B1048576").End(xlUp).Offset(1, 0).Value = response
MsgBox "'" & response & "' successfully entered!"
End If
Case Else
MsgBox "Field is empty!"
Call addNewCust_Click
End Select
End Sub
FOLLOWUP (From Comments)
Select Case is considered to be faster than If-Endif but for such a small scenario, the efficiency comparison is futile. What is more important is how you write the code
Below is another way. I love this way as things are broken down into smaller parts and everything is declared properly. I am not touching error handling below. See this for detailed analysis.
The below method is useful because
when you are looking at your code (say maybe after an year) and you know exactly what is happening since the code is commented.
Easy to maintain the code. For example if the Sheet name changes then you have to change it only at one place. The alternative is to also use Codenames
You can use the same code across all Excel platforms. If you hardcode your range, Ex: Range("B1048576") then the above code will not work in Excel 2003.
Sample Code
Sub addNewCust_Click()
Dim ws As Worksheet
Dim Lrow As Long
Dim response
'~~> Set the relevant worksheet
Set ws = ThisWorkbook.Worksheets("CustomerList")
With ws
Do
'~~> Get user response
response = Application.InputBox(prompt:="", Title:="New customer name", Type:=2)
Select Case response
Case False: Exit Sub '<~~ If user presses cancel or closes using 'X'
Case "": MsgBox "Field is empty!" '<~~ If user enters a blank entry
Case Else
'~~> Check if the entry exists
If WorksheetFunction.CountIf(.Range("B:B"), response) > 0 Then
MsgBox "'" & response & "' already exists on this sheet."
Else
'~~> Get last Row
Lrow = .Range("B" & .Rows.Count).End(xlUp).Row + 1
'~~> Add the new entry
.Range("B" & Lrow).Value = response
MsgBox "'" & response & "' successfully entered!"
Exit Do 'OR Exit Sub (As Applicable)
End If
End Select
Loop
End With
End Sub
I am creatin multiple charts on a single sheet. Lets say I have a sheet "Sheet 1" and on this sheet I am creating 10 charts with name from "chart 1" to "Chart 10". But the problem is when I click the name box,list of all the charts is not available in that name box.
Can any one help me out how to do that through simple excel or excel VBA.
Update: I don't believe anything other than range names or the currently selected object is available in the "name box". The only alteration I have ever seen made to the name box is a width increase
In Xl2010 you can see all the charts using the Selection Pane
Home .... Editing .... Find & Select .... Selection Pane
Original
Something like this would give you the list
Did you want the ability to select a chart from the list and activate it, or just the list itself?
Sub GetCharts()
Dim chr As ChartObject
Dim strOut As String
For Each chr In Sheets(1).ChartObjects
strOut = strOut & chr.Name & vbNewLine
Next
If Len(strOut) > 0 Then
MsgBox "Chart Names are:" & vbNewLine & strOut
Else
MsgBox "No charts", vbCritical
End If
End Sub
The macro below outputs more information about the charts in a workbook and a worksheet than brettdj's. The idea is to give you a fuller indication of the information that is available and how you access it.
However, I do not understand what you want to appear in the Name Box.
Sub Test1()
Dim InxCO As Integer
Dim InxWS As Integer
For InxWS = 1 To Worksheets.Count
With Sheets(InxWS)
Debug.Print "Worksheet: " & .Name
Debug.Print " " & .ChartObjects.Count & " charts"
For InxCO = 1 To .ChartObjects.Count
With .ChartObjects(InxCO)
Debug.Print " Chart: " & .Name
Debug.Print " Location: " & .TopLeftCell.Address & " to " & _
.BottomRightCell.Address
If .Chart.HasTitle Then
Debug.Print " Title: " & .Chart.ChartTitle.Text
Else
Debug.Print " Untitled"
End If
End With
Next
End With
Next
End Sub
If you have Excel 2007+, there is a Selection and Visibility window that you can activate.
To see this,
1) insert ANY shape on your sheet
2) **Format > Arrange > Selection Pane**
You can, at this point, right-click the Selection Pane icon and add it to your QAT. Using the icon on your QAT, means that the Selection and Visibility window can be activated any time, with or without shapes on a sheet.