Change value of check box when its name is the value of a variable - excel

First post so I'll try my best to make it a good one (please tell me if I'm doing it wrong).I can't seem to write the code properly to change the value of a check box or option button on a sheet using a variable.
Suppose the name of the check box name is "Chk1", normally I would write :
Worksheets("AP-1").Chk1.value=X
Where X is (either True or False). Since it is a Loop, I use a range variable called FoundRange and it's value is the name of the check box, so I tried:
dim chkname as string
chkname=foundrange.value
Worksheets("AP-1").Chkname.value=X
I also tried
Worksheets("AP-1").CheckBoxes(chkname).Value = X
and
Worsheets("AP-1").Shapes(chkname).ControlFormat.Value=X
I also had a linked cell that I used to change the value, but when it writes either false or true in it, the check box becomes gray and I need to press F2+Enter in the linked cell to make the check box show the proper value. I also tried to select the linked cell after changing its value and use that code:
Application.SendKeys "{F2}"
Application.SendKeys "{ENTER}"
but it did not work.
Please help me :)

Based on your initial code, it must be an ActiveX control, not a Form one, so:
dim chkname as string
chkname=foundrange.value
Worksheets("AP-1").OLEObjects(Chkname).Object.value = X

Related

HyperLink click runs function twice and give patch error

From title you can already tell what is my problem.
Somethink from my side:
I know there is for sure work around to run the macro once with creating boolean or check and hadling the error (with I still dont know how).
I want to know why the macro runs twice. My guess is that it takes mouse movement or somethink like that.
How to fix it?
Or use better alternative of capturing click on text (I want to evoid selection change/change and I am not big fan of using FollowHyperlink with linking on same cell).
Function I am using : =HYPERTEXTOVÝ.ODKAZ("#LinkClick()";"CLICK")
Eng version : =HYPERLINK("#LinkClick()";"CLICK")
Function LinkClick()
Range("A1").Value = Range("A1").Value + 1
End Function
It should be the same function. It is just different in my language :
https://support.office.com/cs-cz/article/hypertextov%C3%BD-odkaz-funkce-333c7ce6-c5ae-4164-9c47-7de9b76f577f
https://support.office.com/en-us/article/hyperlink-function-333c7ce6-c5ae-4164-9c47-7de9b76f577f?omkt=en-US&ui=en-US&rs=en-US&ad=US
PS: My first post and my english isn't best. Thanks for any answers.
You need to Set LinkClick = Selection so you return a cell with your function otherwise the link is invalid.
According to the documentation your formula =HYPERLINK("#LinkClick()";"CLICK") needs a link_location as first parameter HYPERLINK(link_location, [friendly_name]). But because you have a function call there "#LinkClick()" the function needs to return a valid link location, and that is what Set LinkClick = Selection does, it returns the actual selection as link location, so the hyperlink selects what is already selected (means it does nothing at all, but it doesn't complain about an invalid link location).
Option Explicit
Public Function LinkClick() As Range
Set LinkClick = Selection 'make sure a valid link location is returned in the function
ActiveSheet.Range("A1").Value = ActiveSheet.Range("A1").Value + 1
End Function

Powerapps Visible function

For some reason the Visible function in my Powerapps won't work I just wrote in OnSelect() Mail.Visible = false
The Mail is in this case a Textinput/ TextBox.
When I click on the button nothing happens. I can't find a documentation about it on the MS Website but I have in Powerapps a fuction called "Visible"
You need to create a variable in the button's (or another control) OnSelect property:
UpdateContext({ mailVisible: false })
And set the Visible property of the Mail control to mailVisible. You may need to initialize that variable to true, for example, in the screen's OnVisible property:
UpdateContext({ mailVisible: true })
PowerApps works similarly to Excel - you cannot, by an action, change directly the value of a cell (e.g., A1 = 42). But you can make the A1 cell reference another cell (say, =A4), so when you change the value of the cell A4, A1 will be updated as well. The same principle applies in PowerApps - you cannot change the value of a property from an action, but you can update the value that the property references.
Credit #SeaDude
This worked perfectly for me toggling the variable back and forth to show/hide a few layers.
Set(mailVisible, !mailVisible)
So I have a few items like this. I'm not sure if this is the BEST way but I know it works.
Set a variable on the app start:
App = Set(variable_visable, "");
Button code:
Onselect = Set(variable_visable.,"1");
Item that you want visible:
Visibility = If(variable_visable="1", true, false);
Edit: You can reset your variable at any point to hide that section.
Sometimes power apps fights you on things that seem correct.
The Visible will the condition that is true to make it show.
For example
If I have one TextBox named TextInput1 and I want a control to be visible when the Text entered = true it will be. For this example use a label.
Label1's visible function will be TextInput1.Text = "true"
This will show when the input text will be true. if it's false or anything else the label won't show. This is a very basic use of the visible but can be used in many ways.
In On select property of button you can't set any other control property directly.
you need to follow the steps as:
1- you need to set a boolean type variable on OnSelect of button e.g.
Set(varShowMail,false)
2- go to TextInput Mail and select its Visible property and assign the variable "varShowMail"
It will work 100%.
Set on visible of screen property UpdateContext({ Var_Visible: false})
set a variable on control "select" or "change" to true"UpdateContext({ Var_Visible: true})" and use the variable in other control visible property that you want to show or hide, if required you can use condition to set a variable to true or false

VBA Excel : Populate TextBox with specific string of text when Option Button is selected

I developed a Form in Excel (2016) and I am trying (with VBA) to configure its behavior so that if the user selects a particular option button, two additional things happen:
A checkbox further down on the form is automatically checked.
A text box further down on the form automatically displays a set string of text.
More specifically, if the user selects OptionButtonABC, then ...
CheckBoxNone should become checked
TextBoxCompanyName (which does not display any text by default) should now display the string: 'ABC'.
I initially created a subroutine that just targeted condition 1, and everything worked fine. However, when I try to integrate the code required to handle condition 2, things start to unravel.
Below, you will see the code in its most current state. I have a Private Sub that initiates upon the Click event and then immediately defines a variable as a string. I then set up an if/then statement that specifies what should happen IF OptionButtonABC is true. Namely, CheckBoxNone should be selected (this works fine) AND TextBoxCompanyName should now display the string 'ABC'.
Private Sub OptionButtonABC_Click()
Dim Variable_ABC As String
Variable_ABC = ABC
If Me.OptionButtonABC.Value = True Then
Me.CheckBoxNone = True And Me.TextBoxCompanyName.Text = Variable_ABC
End If
End Sub
The desired behavior should (theoretically) be pretty easy to achieve, but my experience with VBA is still pretty limited, so I am reaching out to the community for a bit of advice. As I mentioned above, the code above works for the first condition. However, I am still unable to get the string of text ('ABC') to show up in the text box.
Thanks in advance for any advice you may offer.
Private Sub OptionButtonABC_Click()
Dim Variable_ABC As String
Variable_ABC = "ABC" 'String Values uses double quotes
If Me.OptionButtonABC.Value = True Then
Me.CheckBoxNone = True
Me.TextBoxCompanyName.Text = Variable_ABC
End If
End Sub
The operator AND must be used only in the IF statement comparison, not in what you want to do.

MS Access: Choosing Worksheet from Excel Workbook

I'm writing some code in MS Access and I reached to the point where user needs to choose on which worksheet of an Excel workbook there need to be performed some operation. I don't know, what name of this worksheet is or on which position it is placed.
I was thinking about a solution which will show user a form (as modal form) with listbox containing all sheets names'. When user click one of them form will show aside A1:J10 range (so user can choose the right one worksheet). After confirming choosen worksheet it will return as worksheet object.
Every thing was great untill I wanted to pass a object variable to the form. In openArgs I can only pass a string. I was even thinking about a class which will open this form but it's still no luck with passing object parameter.
I'm trying to avoid global/public variables.
Any ideas?
Assuming your object is wsObj, can't you just use wsObj.Name ?
Also have a look at wsObj.CodeName, which may be interesting as well.
There are many possibilities to send some value between objects.
A) Using Global vars into ACCESS Vba module
Global yourvariable As String
if you need some different value can use Variant, Single, etc.
B) Using Windows Register
To save value:
SaveSetting "yourprojectname", "Settings", "yourvariable", yourvalue
To retrieve value:
retvalue = GetSetting("yourprojectname", "Settings", "yourvariable", "your_default_value_if_not_exist")
C) Using OpenArg into Open Form command procedure
DoCmd.OpenForm "stDocName", acNormal, "filter_if_needed", "stlinkcriteria", acFormEdit, acWindowNormal, "arguments_forOpenArgs"
On destination form
Private Sub Form_Open(cancel as integer)
your_args=Me.OpenArgs
On all three possible solutions you can send more than one value using a chain with vars and values, an example:
myvar_mutiple="name=John Doe|address=Rua del Percebe 34|location=Madrid|phone=34 91 1234567"
On this example i used "pipe" (AltGr on key 1) char to separate each var=value
Then on destination procedure only need split each pair:
splitvar=Split(myvar_multiple,"|")
With this you obtain for each "splitvar" an element like "name=John Doe"
Do again an split with "=" to obtain variable an value. For each value you can reassign the result to a local vars.
Full code example:
if me.OpenArgs<>"" then
splitvar=Split(me.OpenArgs,"|")
for x=0 to ubound(splitvar)
tmpsplit=Split(splitvar(x),"=")
paramvars=tmpsplit(0)
paramvalue=tmpsplit(1)
select case paramvars
case "name"
stname=paramvalue
case "address"
straddress=paramvalue
case "location"
strlocation=paramvalue
case "phone"
strphone=paramvalue
end select
next
end if
Some recommendations that i use for this code "multiple vars":
- always use Low Case variable or change this:
paramvars=tmpsplit(0)
by
paramvars=lcase(tmpsplit(0))
-if you need to use "=" into value you can change by other alternative char or search the first "=" form left (i used this solution instead Split)
paramvars=trim(lcase(left(splitvar(x),len(splitvar(x))-(len(splitvar(x))-instr(splitvar(x),"="))-1)))
remember that you can send any value and can be converted on destination code. On this sample i use only String so you can use cLng or cInt etc.
Over your solution to select Sheet on excel from Access i think there are better alternatives.
IN the forms Module you can declare a property as object and then set that property once loaded. So in the form module
Option Explicit
Private myObj as object
Property Set DesiredWorksheet(o as object)
set myobj = o
End
and then in your code
Load myform
set myform.desiredworksheet = wsObj
myform.show
Ahh, sorry I was writing Excel not Access!!!
Docmd.openform f
f.desiredworksheet = ws.obj
docmd.openform f, windowmode:=acdialog
ought to work

How to call a macro from a button and pass arguments

I want to add a button to my excel worksheet which should call a macro that can handle one agument (an integer value). Sadly when creating the button, I cannot link any macro that has arguments. Also just typing the macro and the argument does not work.
Is there any simple solution to pass an argument to a macro when a button is pressed?
Yes, you can assign a macro to a button (or other excel controls/menu actions) and pass constant OR variable arguments to it.
In the 'Assign Macro' window (right-click on object and select 'Assign Macro'):
Enclose the macro name in single quotes
e.g. to pass 2 constants: 'Button1_Click("A string!", 7)'
Select 'This Workbook' for the 'Macros in' field
If you wish to pass a variable (like the value of a cell), enclose the parameter in Evaluate()
For example, to pass the value of Sheet1!$A$1 to a button function, you would have the following text in the 'Macro name:' field:
Button1_Click(Evaluate("Sheet1!$A$1"))
If you don't enclose your variable argument with an 'Evaluate' function, excel returns the error 'Formula is too complex to be assigned to an object.'.
I would have included an image if this were allowed on my first post.
Suppose you have a public sub take 1 argument like below (just for explanation purposes.)
And you insert a button on Worksheet like below, and you can not find the macro name when you want to assign your sub to this button.
Now, you can type in your sub name + space + argument manually in single quotes, like below, click ok.
Then you see, problem solved.
Sub ert()
Call ert2(Cells(1,1).Value)
End Sub
Use an activeX control command button and in the button click method, call the sub and pass the argument:
Private Sub CommandButton_Click()
Dim x as Integer
x = 1
Call SomeSub(x)
End Sub
To call this Sub from a button :
Public Sub TestButton(strMessage As String)
MsgBox strMessage
End Sub
... be aware that the Sub won't be listed in the available macros, because it has a parameter. Just type in the call in single quotes : 'TestButton "Hello"'
Called from a regular "forms" button on a worksheet you can do something like this:
Sub TestMe()
Dim c, arr
c = Application.Caller
arr = Split(c, "_")
If UBound(arr) > 0 Then MsgBox "Got " & arr(1)
End Sub
Where the calling button is named (eg) "Button_3"
Or (simpler) right-click the button and enter 'TestMe2 5' (Including the single-quotes)
Sub TestMe2(i)
MsgBox "Got " & i
End Sub
See also: Excel 2010 - Error: Cannot run the macro SelectCell using .onAction
I had trouble with my version of Personal.xlsb!'testForXXXX("Test Test")'. I got an error when clicking the button containing the Macro.
However, I was able to fix it by removing the "(" and ")". So, Personal.xlsb!'testForXXXX "Test Test"' worked (notice the space between testForXXXX and "Test...").
In fact, I didn't need Personal.xlsb! and was just able to use 'testForXXXX "Test Test"'.
I hit the same issue with the assign button not being very useful until I realised that all the potential macros displayed were only the ones in my Personal.xlsb file that took no arguments. Then I typed Personal.xlsb!'macroNameWhichTakesArguments("arg1", ...)' and the sheet picked it up.
I.E. Personal.xlsb!'testForXXXX("Test Test")'
Where the macro testForXXXX take a string as input, then the sheet worked ok.
When you use the assign macro route for a button in excel 2007 at least testForXXXX will not show up in the list of potential macros if it takes args.
I suspect Aaron C got tripped up by this too. Maybe its best not to use a Personal.xlsb file?
I would have liked to comment the answer by QA Collective but I do not have enough reputation point yet. Previous solutions did not work for me, as my macros are in named modules in my VBA project.
With Excel 2013, the way to pass a parameter to a macro using a button that worked in my context is :
'<module name>.<macro name> <parameter>'
e.g
'DataProcessor.disle "myText"'
or
'DataProcessor.editWSProcess True'
(boolean do not need double quotes when passed as parameters)
Please note that single quotes are around the whole expression.

Resources