How to make counting the cells with button in Excel, VBA? - excel

I'm making the simple app using the VBA code and forms in Excel. So, I need to have a simple Private Sub CommandButton1_Click() method which will call for calculation methods and write down the results in Label. How can I do this? (yes, I'm new to VBA)
Private Sub CommandButton1_Click()
MsgBox "My text here"
End Sub
Private Sub UserForm_DblClick(ByVal Cancel As MSForms.ReturnBoolean)
CommandButton1_Click
End Sub
But instead of the calling the window with my text there I need to make calculations of cells.
Will it be correct if I'll write code like shown down there and somehow add the calculations of cells?
Sub Button1_Click()
Sheet1.testing
End Sub
Sub testing()
Dim ell As Object
Dim post As String
Dim Count As Double
Dim cm As String
End Sub

In vba editor, double-click on the command-button in the UserForm to enter the code:
If you put the sub-procedure in the module (e.g doSomething sub-procedure), you have to add the module name:
Call Module1.doSomething
Option Explicit
Private Sub CommandButton1_Click()
Call doSomething
End Sub
'--------------------------------------
Sub doSomething()
MsgBox "My text here"
End Sub

#FunThomas helped me (you can see it in comments to this question). And here is the solution on my question:
Private Sub CommandButton1_Click()
testing
End Sub
Sub testing()
Dim value1
calc = value1 + 10
Label1 = value1 + 10
Dim ell As Object
Dim post As String
Dim Count As Double
Dim cm As String
Dim sText As String
sText = Sheet1.Range("A1").Value
Label2 = sText
End Sub

Related

VBA Userform ComboBox instantiation

I have a Problem with a Userform which I called "ComboTest2". It only consists of two Comboboxes. If I instantiate the USerform as an object then the following Code doesn't work in the sense that the second combobox of the Userform doesn't contain the desired data.
Sub FillCombo(ByVal row As Long)
Dim rgCities As Range
Set rgCities = Worksheets("Tabelle2").Range("B2:D2").Offset(row)
ComboTest2.ComboBox2.Clear
ComboTest2.ComboBox2.List = WorksheetFunction.Transpose(rgCities)
ComboTest2.ComboBox2.ListIndex = 0
End Sub
Sub FillMain()
Dim ComboForm2 As ComboTest2
Set ComboForm2 = New ComboTest2
ComboForm2.Show
End Sub
UserForm-Code:
Private Sub CommandButton1_Click()
Me.Hide
End Sub
Private Sub CommandButton2_Click()
Me.Hide
End Sub
Private Sub ComboBox1_Change()
FillCombo ComboBox1.ListIndex
End Sub
Private Sub UserForm_Initialize()
ComboBox1.List = Worksheets("Tabelle2").Range("A2:A5").Value
ComboBox1.ListIndex = 0
FillCombo ComboBox1.ListIndex
End Sub
But if I use the "default instantiation" by VBA which means that I change the FillMain Sub to:
Sub FillMain2()
Dim ComboForm2 As ComboTest2
Set ComboForm2 = New ComboTest2
'ComboForm2.Show
ComboTest2.Show
End Sub
Then everything is fine. Why is that so?
Best regards
It's because FillCombo is referring to the userform by name, and therefore to the default instance (you're actually creating a new instance of the form). If that code is not in the userform, and I'm not sure why you would have it outside the form, you should pass the combobox as an argument to it.

VBA Userforms Show the Same Userform again and again

currently i am programming a excel macro. The macro shows a Userform.
In the Userform the User can Select something. After the User has selected something i call Userform.Hide to Hide the Userform and to read the Selection from the Form. After the selection was read i call Unload Userform. Now the Code interacts with the selection. I want to do this in a loop but when the Code trys to show the Userform the second time. I get a exception that the Form is already displayed. I cant understand it, because i called Unload Userform. When i do it in debug mode everthing works as it should.
Userform Code
Private Sub Image1_Click()
SelectCard 1
End Sub
Private Sub Image2_Click()
SelectCard 2
End Sub
Private Sub SelectCard(number As Integer)
SelectedNumber = number
Me.Hide
End Sub
Public Sub CardSelector_Activate(Cards As Cards)
Dim c As card
For Each Key In Cards.CardDictionary.Keys
Set c = Cards.CardDictionary.Items(Key - 1)
If c.value = 1 And c.played Then
Image1.Enabled = False
End If
If c.value = 2 And c.played Then
Image2.Enabled = False
End If
Next Key
number = SelectedNumber
CardSelector.Show
End Sub
Code in the ClassModule i call this in a loop
Sub Costum(Spalte As Integer, Zeile As Integer, SpalteBeginn As Integer, Cards As Cards, CardsOpponent As Cards)
CardSelector.CardSelector_Activate Cards
Dim c As card
Dim number As Integer
number = CardSelector.SelectedNumber
Set c = Cards.CardDictionary.Items(CardSelector.SelectedNumber - 1)
SetCardAsPlaced c, Zeile, Spalte, SpalteBeginn
Unload CardSelector
End Sub
Can someone help me here ?
I am not sure if I fully understand your issue, but this is how I invoke a form using VBA. This is assuming you have a Cancel and OK button:
In the form:
Option Explicit
Private m_ResultCode As VbMsgBoxResult
Private Sub btnCancel_Click()
Call CloseWithResult(vbCancel)
End Sub
Private Sub btnOK_Click()
' Store form control values to member variables here. Then ...
Call CloseWithResult(vbOK)
End Sub
Private Sub CloseWithResult(Value As VbMsgBoxResult)
m_ResultCode = Value
Me.Hide
End Sub
Public Function ShowMe(Optional bNewLayerOptions As Boolean = True) As VbMsgBoxResult
' Set Default to Cancel
m_ResultCode = vbCancel
' Execution will pause here until the form is Closed or Unloaded
Call Me.Show(vbModal)
' Return Result
ShowMe = m_ResultCode
End Function
Then, to call it (please note that frmLayers is my own VBA form object - you would use yours):
Dim dlgLayers As New frmLayers
If (dlgLayers.ShowMe(False) = vbOK) Then
' Proceeed
End If
Does this help you with your issue? I am sorry if I have misunderstood, and I will remove my answer if needed.
Things like xxxxx_Activate etc. are event handlers called by the framework. So, for example, there is an event for activate and an event for initialize. You don't normally have to directly call these yourself if you set your code up correctly. See https://support.microsoft.com/en-us/kb/138819.

VBA Pass Form Controls to Function

All,
I have been struggling with this for a while: is it possible to pass an object to a function?
Here is what I am trying to accomplish:
Get the name of which control was pressed on a form (as object?)
Send the control's name to function "MyFunction" (as reference?)
Disable that same control on "MyFunction"
Called from form1:
Private Sub button1_Click()
Dim caller As String
caller = Form1.ActiveControl.Name
MyFunction(caller)
End Sub 'I'm able to pass it as a string
button1_Click calls MyFunction and passes caller to it:
Private Sub MyFunction(caller As String)
caller.Enabled = False
End Sub
I understand this will not work as a string. How could I possibly do it as an actual object?
Thank you!
There is little problem passing an object to a sub:
Private Sub Disable(c As Control)
MsgBox c.Name
c.Enabled = False
End Sub
Private Sub CommandButton1_Click()
Disable CommandButton1
End Sub
Private Sub CommandButton2_Click()
Disable CommandButton2
End Sub
Private Sub CommandButton3_Click()
Disable CommandButton3
End Sub
In the above I created a userform with three buttons, they say who they are when clicked and are then disabled.
Note that
Disable CommandButton1
can be replaced by
Disable Me.ActiveControl
or even just
Disable ActiveControl
You can even use Variant like so (rough example):
Private Sub CommandButton1_Click()
EnableDisable ActiveControl, "disable"
End Sub
Private Sub EnableDisable(control As Variant, status As String)
If status = "enabled" Then
control.Enabled = True
Else
control.Enabled = False
End If
End Sub
John Coleman's example is better than mine, though.

Excel VBA editor auto-UNcapitalizing properties

Usually the Excel VBA editor auto-capitalizes keywords and property names for you, but now it is un-capitalizing them. Like this:
Private Sub CommandButton1_Click()
Range("A1").Value = "test"
End Sub
changes to:
Private Sub CommandButton1_Click()
Range("A1").value = "test"
End Sub
And then the code doesn't run properly. Any ideas what could cause this behavior? Thanks.
Possible reasons
You have named one of the modules as value
You have a variable called value in one of your procedures/functions
You have a procedure/function with that name
Example for point 1
Example for point 2
Sub Sample()
Range("A1").value = "Sid"
End Sub
Sub Blah()
Dim value As Long
value = 1
End Sub
Example for point 3
Sub Sample()
Range("A1").value = "Sid"
End Sub
Sub value()
'
'
'
End Sub

"Ok" command box in userform

basically I have a userform which I would like to use to enter 2 data into another macro which I already have. The userform is as below:
Basically, I would like the OK button to be clicked and the data in the two boxes will be entered into another macro that I have. It would also be great if the OK button can help in a sense that it will prompt a warning if one of the boxes is not filled up.
So far, I do not have much of a code for this..
Private Sub UserForm_Click()
TextBox1.SetFocus
Sub Enterval()
End Sub
Private Sub TextBox1_Change()
Dim ID As String
ID = UserForm3.TextBox1.Value
End Sub
Private Sub TextBox2_Change()
Dim ID2 As String
ID2 = UserForm3.TextBox2.Value
End Sub
Private Sub OKay_Click()
Enterval
End Sub
Would appreciate any tips and help. Thanks!
My other macro
Private Sub CommandButton1_Click()
Dim Name As String
Dim Problem As Integer
Dim Source As Worksheet, Target As Worksheet
Dim ItsAMatch As Boolean
Dim i As Integer
Set Source = ThisWorkbook.Worksheets("Sheet1")
Set Target = ThisWorkbook.Worksheets("Sheet2")
Name = Source.Range("A3")
Problem = Source.Range("I13")
Do Until IsEmpty(Target.Cells(4 + i, 6)) ' This will loop down through non empty cells from row 5 of column 2
If Target.Cells(4 + i, 6) = Name Then
ItsAMatch = True
Target.Cells(4 + i, 7) = Problem ' This will overwrite your "Problem" value if the name was already in the column
Exit Do
End If
i = i + 1
Loop
' This will write new records if the name hasn't been already found
If ItsAMatch = False Then
Target.Cells(3, 6).End(xlDown).Offset(1, 0) = Name
Target.Cells(4, 6).End(xlDown).Offset(0, 1) = Problem
End If
Set Source = Nothing
Set Target = Nothing
End Sub
Thats the macro i have. As u said, i change the
othermacro
to CommandButton1_Click()
but it doesn't work
Quoting geoB except for one thing: when you .Show your UserForm from a main Sub, you can also .Hide it at the end and the macro that called it will continue its procedures.
Sub Okay_Click()
Dim sID1 As String, sID2 As String
' A little variation
If Me.TextBox1 = "" Or Me.TextBox2 = "" Then
MsgBox "Please fill all the input fields"
Exit Sub
End If
Me.Hide
End Sub
To address your TextBox, you can write in your main Sub UserForm3.TextBox1 for example
There is no need for an Enterval function. Instead, assume the user can read and follow instructions, then test whether that indeed is the case. Note that in your code ID and ID2 will never be used because they exist only within the scope of the subroutines in which they are declared and receive values.
To get started:
Sub Okay_Click()
Dim sID1 As String, sID2 As String
sID1 = UserForm3.TextBox1.Value
sID2 = UserForm3.TextBox2.Value
If Len(sID1 & vbNullString) = 0 Then
MsgBox "Box A is empty"
Exit Sub
End If
If Len(sID2 & vbNullString) = 0 Then
MsgBox "Box B is empty"
Exit Sub
End If
'Now do something with sID1, sID2
otherMacro(sID1, sID2)
End Sub
For your other macro, declare it like this:
Sub otherMacro(ID1, ID2)
...
End Sub
Also, the SetFocus method should occur in the form open event.

Resources