How to trigger enter keypress of all textboxes in multiple sheets? - VBA - excel

My workbook has three sheets(named Sheet1 ~ Sheet3) with TEXTBOXES.
This has a module.
Public dontDoThat As Boolean ' a public variable, visible throughout all your project you'll use to give way to synchronizing activity
Option Explicit
Sub Synchronize(txt As String, shtName As String)
dontDoThat = True ' set your public variable to True and prevent subsequent TextBox1_Change() events to run it again
Dim sht As Variant
For Each sht In Array("Sheet1", "Sheet2", "Sheet3")
If sht <> shtName Then Worksheets(sht).TextBox1.Text = txt
Next
dontDoThat = False ' set your public variable to False and allow subsequent TextBox1_Change() events to run it
End Sub
These code can synchronize the TEXTBOX on all sheets.
But It's only for Text.
If I type some text in TEXTBOX1 of Sheet1, the same text will be display in TEXTBOX1 of all other sheets.
but The search function does not work on other sheets.
After I typed some text on TEXTBOX1 of Sheet1 and When I press the enter key, The search function works only in Sheet1.
I want to trigger the enter keypress on Textboxes of all Sheets.
And these sheets also have TEXTBOX2.
Thus I want to know how to apply syncronization to TEXTBOX1 and TEXTBOX2 as well.
I need someone help.

Neo, I've done something like this before - where you create an autofilter either with Change event, or a specified KeyDown event (usually the Enter key - vbKeyReturn). Since you're using a KeyDown event, it wouldn't be overly exhaustive to use collections. You can, say, roll all of your TextBoxes in a collection either by name similarities, or by TypeName.
Specifically, for why I'm thinking you're having issues, perhaps loop through the Worksheets collection with an actual Worksheet object, and not a variant. And, since they're Worksheets objects, you can use OLEObjects.
Dim sht As WorkSheet
Dim x as Integer
x = 1
For Each sht In ThisWorkbook.WorkSheets
Do Until sht.OLEObjects("TextBox & x") is Nothing
If sht.Name <> shtName Then sht.OLEObjects("TextBox & x").Object.Text = txt
x = x + 1
Loop
Next
And even within that loop, you can do another loop to iterate over your multiple text boxes. Let us know how you want to proceed. Hope this helps...

Related

How can I add sheets from an excel file to another?

So I am trying to write a Macro for Excel, that adds 2 worksheets from an excel file to a new one.
Therefore, I try this:
Sub addfile()
Dim sheet1 As Worksheet
Dim sheet2 As Worksheet
Set sheet1 = Sheets.Add(Type:="C:\Users\Helge\AppData\Roaming\Microsoft\Templates\page1.xltx")
Set sheet2 = Sheets.Add(Type:="C:\Users\Helge\AppData\Roaming\Microsoft\Templates\page2.xltx")
End Sub
When I test it, it imports the first page, but the 2nd page gives me a Runtime error 1004.
Why does this happen?
And is there another way to get 2 sheets from one excel file to another via vba?
Much to my surprise this version of your code actually worked for me.
Sub addfile()
Dim Sheet1 As Worksheet
Dim Sheet2 As Worksheet
Set Sheet1 = Sheets.Add(Type:=Environ("Userprofile") & "\OneDrive\Desktop\Template1.xltx")
Set Sheet2 = Sheets.Add(Type:=Environ("Userprofile") & "\OneDrive\Desktop\Book2.xlsx")
Debug.Print Sheet1.Name, Sheet2.Name
End Sub
The reason for my surprise is that Sheet1 and Sheet2 are the default CodeName for the first and second worksheets in any workbook. Therefore there is a conflict of naming between the Sheet1 in the workbook and the Sheet1 you declare which should come to the surface not later than Debug.Print Sheet1.Name. In fact, it may have. I didn't check which name was printed. But the code didn't crash. Since it crashes on your computer, perhaps you have an older version of Excel. Try to stay clear of variable names that Excel also uses. Or there is something wrong with the path & file name, which is hard to tell in that syntax and therefore kept me fooled for quite some time too.
In fact, I discovered the above only after finding out that my Desktop was on OneDrive and not before I had written the function below which is designed to avoid the use of Sheets.Add. It also has some extras such as being able to specify the sheet to take from the template (you could have one template with 2 or more sheets). You can specify an index number or a sheet name. And the function will give a name to the copy, too, if you specify one.
Private Function AddWorksheet(ByVal Template As String, _
TabId As Variant, _
Optional ByVal TabName As String) As Worksheet
Dim Wb As Workbook
Dim Path As String
Dim FileName As String
Set Wb = ThisWorkbook ' change to suit
' make sure the path ends on "\"
Path = "C:\Users\Helge\AppData\Roaming\Microsoft\Templates\"
With Workbooks.Open(Path & Template)
.Sheets(TabId).Copy After:=Wb.Sheets(Wb.Sheets.Count)
.Close
End With
Set AddWorksheet = ActiveSheet
If Len(TabName) Then ActiveSheet.Name = TabName
End Function
You can call the function from a sub routine like this:-
Sub AddWorksheets()
Dim Tab1 As Worksheet
Dim Tab2 As Worksheet
Application.ScreenUpdating = False
Set Tab1 = AddWorksheet("Page1.xltx", 1, "New Tab")
Set Tab2 = AddWorksheet("Page2.xltx", "Sheet1", "Another new Tab")
Application.ScreenUpdating = True
End Sub
Please observe the difference between the two function calls.

Loop thru controls on another workbooks userform

OK I have searched and searched on how to do this properly. Here goes. I have 2 workbooks. In the first workbook I have some userforms (nested userforms that create a user interface for data input that is then saved to worksheets). Each userform of course has controls. The 2nd workbook has the macros. I have a read and write macro in this workbook that is invoked at appropriate times for reading and writing. In some cases, I have special write scenarios that require a little more processing. I have been able to use the application.run approach to run the macros in the 2nd workbook from the 1st workbook userforms.
Here's where I'm stomped. The times where I have to special write scenarios, in order to do this, while in the 2nd workbook's macros, I need to refer back to the 1st workbook launch an alternative userform and then loop thru the controls (textboxes) and update certain textbox values. To attempt this, I was performing 'Application.Run ("'" & wb.Name & "'!showNA")' which will open and initialize the other userform in the 1st workbook. Then I want to loop thru it's controls using 'For Each ctrl In vbcompfrm.Designer.Controls' of which I can not get to work and have tried many different syntax and combinations. Help! I do have the extensibility reference checked in tools as well. I am a self taught vba hobbyist so please go easy on my approach :D Thank you so much.
'code in workbook 2'
Public Sub test(ByRef FRM)
Dim ctrl As MSForms.Control
Dim vbcompfrm As VBComponent
Dim SubStr As String
Dim MyArr() As Variant
Dim key As String
Dim ATTR As String
ReDim MyArr(1)
MyArr(0) = "first"
MyArr(1) = "second"
Set ws = wb.Worksheets("testws")
Application.Run ("'" & wb.Name & "'!showNA") 'this will show the userform NA form the first workbook'
'Application.Run ("'" & wb.Name & "'!hideNA")
With UserForms("tbls_RTU_NA")
Set vbcompfrm = wb.VBProject.VBComponents("NA") 'this is the userform in the first workbook, we want to loop thru the controls'
For Each ctrl In vbcompfrm.Designer.Controls 'not sure how to make this work'
With ctrl
For i = LBound(MyArr) To UBound(MyArr)
If .ControlTipText = MyArr(i) Then
datasplit = Split(MyArr(i), "_")
key = datasplit(0)
ATTR = datasplit(1)
.Text = SearchDataArray(StandardTableDataArray, "NA_" & key, ATTR) 'don't forget we need to set the value of the new text to the array value once we match the key
End If
Next i
End With
Next ctrl
End With

Switching sheets via a dropdown list

I'm very new to VBA, and am trying to create a way to navigate sheets in a workbook via a dropdown list on a main 'index' page. As there are multiple sheets in the workbook, and multiple people using, I would like the dropdown list to autofill, to save from needing to search through the list. I would then like the selected sheet to open (possibly with a macro button, or even by hitting enter if that is an option).
So far, I have the following macro that populates the dropdown list (taken from another site):
Private Sub ComboBox1_DropButtonClick()
Dim xSheet As Worksheet
On Error Resume Next
Application.ScreenUpdating = False
Application.EnableEvents = False
If ComboBox1.ListCount <> ThisWorkbook.Sheets.Count Then
ComboBox1.Clear
For Each xSheet In ThisWorkbook.Sheets
ComboBox1.AddItem xSheet.Name
Next xSheet
End If
Application.EnableEvents = True
Application.ScreenUpdating = True
End Sub
This is perfect for the content of my dropdown list, and for its autofill feature; but I'm struggling to include that final action of actually going to the selected sheet. For info, I've used a ComboBox (ActivX Control). I was thinking it could be a case of creating a macro button and referencing the text in the dropdown selection?
Any help or suggestions would be much appreciated.
You can use the value in the combobox to switch tabs like this. Once I hit the button, then Sheet1 becomes active instead of Sheet2
Here's the code for you to copy/paste & test for yourself:
Private Sub CommandButton1_Click()
Dim mySheet As Worksheet
For Each mySheet In ActiveWorkbook.Worksheets
If mySheet.Name = ComboBox1 Then
mySheet.Select
Exit For
End If
Next mySheet
End Sub
Essentially, this will cycle through all your worksheets to find whatever is in the combobox. If there's a match, then it is selected.

Refereshing formula in workbook when two workbooks are open fills data in incorrectly

Problem with workbooks that share user formula names in excel 2016/excel 365.
I have two workbooks open that both specify a user function GetData.
This function is defined in both workbooks and is not public.
Lets use workbook 1 and workbook 2.
I refresh all formula in workbook 1 using ctrl-shift-alt-F9
All cells using the user defined function in workbook 1 update correctly.
All cells using the custom functions in workbook 2 update using data from workbook 1.
Problem is reversed if using ctrl-shift-alt-F9 in workbook 2.
If I update each cell individually by selecting and pressing enter then the cell uses the correct data. The problem only happens when I force excel to update formula, which is required as its the only way to get multiple formula to update.
I have made sure none of my data tables are defined publicly, my functions are not defined publicly.
Both sheets are identical and use the same code, but with different data.
Here is the code from ThisWorkBook
Sub workbook_Open()
If Worksheets("Background").Cells(1, 1).Value = 1 Then
'Define worksheets for use in workbook'
Dim PersonData As Worksheet:
Set PersonData = Worksheets("Person")
CreateTableReference PersonData, "PersonDataTable"
End If
End Sub
here is the code from the module
Function TableExistsOnSheet(ws As Worksheet, sTableName As String) As Boolean
TableExistsOnSheet = ws.Evaluate("ISREF(" & sTableName & ")")
End Function
Sub CreateTableReference(ws As Worksheet, sTableName As String)
If TableExistsOnSheet(ws, sTableName) Then
ws.ListObjects(sTableName).Unlist
End If
If ws.Cells(1, 1).Value <> "" Then
xLastCol = ws.Cells(1, ws.Columns.Count).End(xlToLeft).Column
xLastRow = ws.Cells(ws.Columns.Count, 1).End(xlUp).Row
ws.ListObjects.Add(xlSrcRange, ws.Range(ws.Cells(1, 1), ws.Cells(xLastRow, xLastCol)), , xlYes).Name = sTableName
End If
End Sub
Function GetData(dataType As String, fieldName As String) As String
Application.Volatile
Select Case dataType
Case "PersonData"
GetData = WorksheetFunction.VLookup(fieldName, Range("PersonDataTable"), 3, False)
End Select
End Function
EXAMPLE OF USE
=GetData("PersonData","Surname")
Expected result would be when ctrl-shift-alt-F9 is pressed that each workbook is updated correctly using the result of the formula using data from its own workbook.
Worksheet Person has the sample data
Data Desription Value
Surname Surname Thomas
my functions are not defined publicly
Even though you did not use the word Public, your functions in the module are still public. i.e they are available within the project containing the module and also to other applications or projects.
You may want to see this Function statement
In scenarios where you have same funciton names in other Excel Applications/Projects, I recommend using Option Private Module
You may want to see Option Private statement
So your code in 1st file will be
Option Private Module
Function Sample()
MsgBox "Blah"
End Function
and in the other as
Option Private Module
Function Sample()
MsgBox "Blah Blah"
End Function
Now each function will refer to it's own module.

How to use autofilter from one workbook to another?

I am trying to get a database from Workbook B to autofilter using some input from Workbook A. I am building the macro in Workbook A.
I have the following:
Workbook A - Document were you start working
Worrkbook B - Database, the final objective of this code is to import some info from Workbook B to Workbook A
I need the following:
By double clicking in a column from workbook A, workbook B should open (done)
The clicked value from workbook A will be saved as a variable, lets call it input_db (done)
Workbook B will autofilter based on input_db (not done, help required here!)
The required data is selected from workbook B and imported to workbook A, preferably with a double click as well (not done yet, but if you have any suggestion for this, Ill be gratefull ;))
The process should be repeated several times in a row.
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
Dim input_row, input_column As Integer
Dim input_db As String
Dim wbB, wbA As Workbooks
If Not (Application.Intersect(ActiveCell, [Links]) Is Nothing) Then 'Links is the name of the range where I need the code to be active
If ActiveCell.Value <> "" Then
input_row = ActiveCell.row
input_column = ActiveCell.Column
input_db = ActiveCell.Value
Set database = Workbooks.Open("Workbook B location")
ActiveWorkbook.ActiveSheet.Range("A9").AutoFilter Field:=1, Criteria:=input_db ' This bit doesnt work as expected
End If
End If
End Sub
As I can see you are using the wrong format of Autofilter. Try this line after amending as per your need. Autofilter takes in Criteria1 not Criteria.
ActiveWorkbook.ActiveSheet.Range("A9").AutoFilter Field:=1, Criteria1:=input_db
Also you can find more about Autofilter here: Link
Let us know if it still doesn't work.
Edit 2 :
You will have to open a input box and select the cell. You can follow the This Link for that.

Resources