Using variable as a label control name - vb6

In VB 6 How can I refer to control label using a variable instead of a fixed name such as LUH01 (as below) which does not allow a Loop.
Frm_Dispo_Prof_Grille.LUH01.BackColor = &HFF00&

You can refer to it via the Controls Collection:
Frm_Dispo_Prof_Grille.Controls("LUH01").BackColor = &HFF00&
Be careful, however. If you need to refer to a property/method that is not one of the standard/built-in ones, you'll have to cast the control to a type:
Dim lbl as Label
Set lbl = Frm_Dispo_Prof_Grille.Controls("LUH01")
lbl.BackColor = &HFF00

I think you want to create a control array
You can do that by creating 1 control, and set its Index property to 0 (instead of empty)
You can then Load new controls and use them all in a loop
For example to load some command buttons and position them in a loop:
'1 form with :
' 1 command button: name=Command1 index=0
'Number of command buttons to use in the loop
Private Const NRBUTTONS As Integer = 5
Option Explicit
Private Sub Form_Load()
Dim intIndex As Integer
'change the caption of the default button
Command1(0).Caption = "Button 0"
For intIndex = 1 To NRBUTTONS - 1
'load an extra command button
Load Command1(intIndex)
'change the caption of the newly loaded button
Command1(intIndex).Caption = "Button " & CStr(intIndex)
'newly load command buttons are invisible by deafult
'make the new command button visible
Command1(intIndex).Visible = True
Next intIndex
End Sub
Private Sub Form_Resize()
'arrange all loaded command buttons via a loop
Dim intIndex As Integer
Dim sngWidth As Single
Dim sngHeight As Single
sngWidth = ScaleWidth
sngHeight = ScaleHeight / NRBUTTONS
For intIndex = 0 To NRBUTTONS - 1
Command1(intIndex).Move 0, intIndex * sngHeight, sngWidth, sngHeight
Next intIndex
End Sub

Related

VB6 How to return a string value from form2 to form 1

in my project there are two forms:
first form i named it frmSettings , i will use text boxes to save values in INI file.
second form i named it frmSelectFolder , i had included with DirListBox and 2 Command buttons
as shown in attached image above in Settings form i have 8 text boxes and 8 command buttons to browse for folder path that it will be selected from frmSelectFolder
how to use frmSelectFolder for all text boxes without duplicating this form per each command button to return DirlistBox Control value ?
Here is some sample code for secondary frmSelectFolder form
Option Explicit
Private m_bConfirm As Boolean
Public Function Init(sPath As String) As Boolean
Dir1.Path = sPath
Show vbModal
If m_bConfirm Then
sPath = Dir1.Path
'--- success
Init = True
End If
Unload Me
End Function
Private Sub cmdOk_Click()
If LenB(Dir1.Path) = 0 Then
MsgBox "Please select a path!", vbExclamation
Exit Sub
End If
m_bConfirm = True
Visible = False
End Sub
Private Sub cmdCancel_Click()
Visible = False
End Sub
Private Sub Form_QueryUnload(Cancel As Integer, UnloadMode As Integer)
If UnloadMode <> vbFormCode Then
Cancel = 1
Visible = False
End If
End Sub
Here is how to call Init method above from primary frmSettings
Option Explicit
Private Sub cmdStartupPath_Click()
Dim sPath As String
Dim oFrmSelector As New frmSelectFolder
sPath = txtStartupPath.Text
If oFrmSelector.Init(sPath) Then
txtStartupPath.Text = sPath
txtStartupPath.SetFocus
End If
End Sub
Private Sub cmdDownloadPath_Click()
Dim sPath As String
Dim oFrmSelector As New frmSelectFolder
sPath = txtDownloadPath.Text
If oFrmSelector.Init(sPath) Then
txtDownloadPath.Text = sPath
txtDownloadPath.SetFocus
End If
End Sub
Here is a link to a complete sample project for you to research: SelectFolder.zip

How to draw a line inside the form to connect two objects in vb6

I am making a flowchart program. I did all of them, but I faced to this problem.
How to draw a line( a connection line) dynamically between two buttons in visual basic through getting a position of a mouse!!
So here's the code of it. I did how to get a position of a cursor, but i cant move forward.
Option Explicit
Private Type POINTAPI
x As Long
y As Long
End Type
Private Declare Function GetCursorPos Lib "user32" _
(lpPoint As POINTAPI) As Long
Dim z As POINTAPI
Private Sub Form_Load()
Timer1.Interval = 1
Timer1.Enabled = True
End Sub
Private Sub Timer1_Timer()
GetCursorPos z
Label1 = "x: " & z.x
Label2 = "y: " & z.y
End Sub
Please help me guys to fix this problem!!
Thanks in advance
Why do you need the position of the mouse?
have a look at the following test project:
'1 form with:
' 2 command buttons: name=Command1 name=Command2
Option Explicit
Private Sub ConnectButtons(cmd1 As CommandButton, cmd2 As CommandButton)
Dim sngX1 As Single, sngX2 As Single
Dim sngY1 As Single, sngY2 As Single
With cmd1
sngX1 = .Left + .Width
sngY1 = .Top + .Height / 2
End With 'cmd1
With cmd2
sngX2 = .Left
sngY2 = .Top + .Height / 2
End With 'cmd2
Line (sngX1, sngY1)-(sngX2, sngY2)
End Sub
Private Sub Form_Click()
ConnectButtons Command1, Command2
End Sub
Private Sub Form_Resize()
Command1.Move 120, 120
Command2.Move ScaleWidth / 2, ScaleHeight / 2
End Sub
When you run it, it will show 2 command buttons on a form, when you click on the form it will draw the connecting line
Resize the form to change the position of Command2 and click the form again
Pay attention to the order of Command buttons you pass to the ConnectButtons sub

Errror when trying to set the text of a ComboBox control

This is my code that tries to set the text of a ComboBox when I click an item in a ListView.
Private Sub ListView1_Click()
If ListView1.ListItems.Count > 0 Then
Text1.Text = ListView1.ListItems(ListView1.SelectedItem.Index).Text
Text2.Text = ListView1.ListItems(ListView1.SelectedItem.Index).ListSubItems(1).Text
Sql = "SELECT A.AID,B.LOC_NAME,C.SNAME FROM ASSET A,LOCATION B,SUPPLIER C WHERE "
Sql = Sql + "A.LOC_ID=B.LOC_ID AND A.SUP_ID=C.SUP_ID AND AID=" & Text1.Text
RS.Open Sql, CON, 1, 2
COM1
Combo1.Text = RS!LOC_NAME //combo with style - 2
COM5
Combo5.Text = RS!SNAME //combo with style - 2
End If
End Sub
Private Sub COM5()
If Combo5.ListIndex = -1 Then
For I = 0 To Combo5.ListCount - 1
Combo5.ListIndex = I
Next
End If
End Sub
Private Sub COM1()
If Combo1.ListIndex = -1 Then
For I = 0 To Combo1.ListCount - 1
Combo1.ListIndex = I
Next
End If
End Sub
However, when I click on the ListView1, I get this error:
'text' property is read only
Can anyone explain why?
For a combobox with the dropdown list style you can only select an item with .text if that item already exists, so combo1.text = "xxx" errors if "xxx" is not present in the list.
To select or add based on existence you can;
Private Sub SelectOrAddToCombo(combo As ComboBox, value As String)
Dim i As Long
With combo
For i = 0 To combo.ListCount - 1
If StrComp(.List(i), value, vbTextCompare) = 0 Then
combo.ListIndex = i
Exit Sub
End If
Next
.AddItem value
.ListIndex = .NewIndex
End With
End Sub
...
SelectOrAddToCombo Combo1, RS!LOC_NAME
SelectOrAddToCombo Combo5, RS!SNAME
It's not clear what the point of your COM5()/COM1() routines are.
For the listview, rather than click look at the
ListView1_ItemClick(ByVal Item As MSComctlLib.ListItem)
event which passes you the clicked item negating the need for ListView1.SelectedItem (which can cause errors if its Nothing).
yes, you must populate the combobox with the array(using additem value) before set the .text propierty, if the text that you want to set on the combobox does not exits in the array you get this error

Applying a command on many objects ? VB6

thanks for reading.
I'm writing a program to create a list consisting of 8 cols. so there are8 listboxes and a textbox under each one.
I want to check each textbox one by one if anyone is empty or not. ...and dunno how to do that!
I need your help!
thanks
instead of using 8 listboxes you might consider using a flexgrid control
but using 8 listboxes and 8 textboxes, you can create them as an array and check them as follows :
'1 form with with
' 1 listbox : name=List1 index=0
' 1 textbox : name=Text1 index=0
' 1 commandbutton : name=Command1
Option Explicit
Private Sub Command1_Click()
If IsEmpty Then
MsgBox "Textboxes are all empty", vbInformation, "IsEmpty"
Else
MsgBox "At least 1 Textbox is not empty", vbInformation, "IsEmpty"
End If
End Sub
Private Sub Form_Load()
Dim intIndex As Integer
For intIndex = 1 To 7
Load List1(intIndex)
Load Text1(intIndex)
List1(intIndex).Visible = True
Text1(intIndex).Visible = True
Next intIndex
Move 0, 0, 10000, 10000
End Sub
Private Function IsEmpty() As Boolean
Dim intIndex As Integer
Dim blnEmpty As Boolean
blnEmpty = True
For intIndex = 0 To Text1.Count - 1
If Len(Text1(intIndex).Text) > 0 Then
blnEmpty = False
Exit For
End If
Next intIndex
IsEmpty = blnEmpty
End Function
Private Sub Form_Resize()
Dim intIndex As Integer
Dim sngWidth As Single
Dim sngListWidth As Single, sngListHeight As Single
Dim sngTextHeight As Single
Dim sngCmdHeight As Single
sngWidth = ScaleWidth
sngListWidth = sngWidth / List1.Count
sngTextHeight = 315
sngCmdHeight = 315
sngListHeight = ScaleHeight - sngTextHeight - sngCmdHeight
For intIndex = 0 To List1.Count - 1
List1(intIndex).Move intIndex * sngListWidth, 0, sngListWidth, sngListHeight
Text1(intIndex).Move intIndex * sngListWidth, sngListHeight, sngListWidth, sngTextHeight
Next intIndex
Command1.Move 0, sngListHeight + sngTextHeight, sngWidth, sngCmdHeight
End Sub

How to add events to Controls created at runtime in Excel with VBA

I would like to add a Control and an associated event at runtime in Excel using VBA but I don't know how to add the events.
I tried the code below and the Button is correctly created in my userform but the associated click event that should display the hello message is not working.
Any advice/correction would be welcome.
Dim Butn As CommandButton
Set Butn = UserForm1.Controls.Add("Forms.CommandButton.1")
With Butn
.Name = "CommandButton1"
.Caption = "Click me to get the Hello Message"
.Width = 100
.Top = 10
End With
With ThisWorkbook.VBProject.VBComponents("UserForm1.CommandButton1").CodeModule
Line = .CountOfLines
.InsertLines Line + 1, "Sub CommandButton1_Click()"
.InsertLines Line + 2, "MsgBox ""Hello!"""
.InsertLines Line + 3, "End Sub"
End With
UserForm1.Show
The code for adding a button at runtime and then to add events is truly as simple as it is difficult to find out. I can say that because I have spent more time on this perplexity and got irritated more than in anything else I ever programmed.
Create a Userform and put in the following code:
Option Explicit
Dim ButArray() As New Class2
Private Sub UserForm_Initialize()
Dim ctlbut As MSForms.CommandButton
Dim butTop As Long, i As Long
'~~> Decide on the .Top for the 1st TextBox
butTop = 30
For i = 1 To 10
Set ctlbut = Me.Controls.Add("Forms.CommandButton.1", "butTest" & i)
'~~> Define the TextBox .Top and the .Left property here
ctlbut.Top = butTop: ctlbut.Left = 50
ctlbut.Caption = Cells(i, 7).Value
'~~> Increment the .Top for the next TextBox
butTop = butTop + 20
ReDim Preserve ButArray(1 To i)
Set ButArray(i).butEvents = ctlbut
Next
End Sub
Now you need to add a Class Module to your code for the project. Please remember it's class module, not Standard Module.
The Object butEvents is the button that was clicked.
Put in the following simple code (in my case the class name is Class2).
Public WithEvents butEvents As MSForms.CommandButton
Private Sub butEvents_click()
MsgBox "Hi Shrey from " & butEvents.Caption
End Sub
That's it. Now run it!
Try this:
Sub AddButtonAndShow()
Dim Butn As CommandButton
Dim Line As Long
Dim objForm As Object
Set objForm = ThisWorkbook.VBProject.VBComponents("UserForm1")
Set Butn = objForm.Designer.Controls.Add("Forms.CommandButton.1")
With Butn
.Name = "CommandButton1"
.Caption = "Click me to get the Hello Message"
.Width = 100
.Top = 10
End With
With objForm.CodeModule
Line = .CountOfLines
.InsertLines Line + 1, "Sub CommandButton1_Click()"
.InsertLines Line + 2, "MsgBox ""Hello!"""
.InsertLines Line + 3, "End Sub"
End With
VBA.UserForms.Add(objForm.Name).Show
End Sub
This permanently modifies UserForm1 (assuming you save your workbook). If you wanted a temporary userform, then add a new userform instead of setting it to UserForm1. You can then delete the form once you're done with it.
Chip Pearson has some great info about coding the VBE.
DaveShaw, thx for this code man!
I have used it for a togglebutton array (put a 'thumbnail-size' picture called trainer.jpg in the same folder as the excel file for a togglebutton with a picture in it). In the 'click' event the invoker is also available (by the object name as a string)
In the form:
Dim CreateTrainerToggleButtonArray() As New ToggleButtonClass
Private Sub CreateTrainerToggleButton(top As Integer, id As Integer)
Dim pathToPicture As String
pathToPicture = ThisWorkbook.Path & "\trainer.jpg"
Dim idString As String
idString = "TrainerToggleButton" & id
Dim cCont As MSForms.ToggleButton
Set cCont = Me.Controls.Add _
("Forms.ToggleButton.1")
With cCont
.Name = idString
.Width = 20
.Height = 20
.Left = 6
.top = top
.picture = LoadPicture(pathToPicture)
End With
ReDim Preserve CreateTrainerToggleButtonArray(1 To id)
Set CreateTrainerToggleButtonArray(id).ToggleButtonEvents = cCont
CreateTrainerToggleButtonArray(id).ObjectName = idString
End Sub
and a class "ToggleButtonClass"
Public WithEvents ToggleButtonEvents As MSForms.ToggleButton
Public ObjectName As String
Private Sub ToggleButtonEvents_click()
MsgBox "DaveShaw is the man... <3 from your friend: " & ObjectName
End Sub
Now just simple call from UserForm_Initialize
Private Sub UserForm_Initialize()
Dim index As Integer
For index = 1 To 10
Call CreateTrainerToggleButton(100 + (25 * index), index)
Next index
End Sub
This was my solution to add a commandbutton and code without using classes
It adds a reference to allow access to vbide
Adds the button
Then writes a function to handle the click event in the worksheet
Sub AddButton()
Call addref
Set rng = DestSh.Range("B" & x + 3)
'Set btn = DestSh.Buttons.Add(rng.Left, rng.Top, rng.Width, rng.Height)
Set myButton = ActiveSheet.OLEObjects.Add(ClassType:="Forms.CommandButton.1", Left:=rng.Left, Top:=rng.Top, Height:=rng.Height * 3, Width:=rng.Width * 3)
DoEvents
With myButton
'.Placement = XlPlacement.xlFreeFloating
.Object.Caption = "Export"
.Name = "BtnExport"
.Object.PicturePosition = 1
.Object.Font.Size = 14
End With
Stop
myButton.Object.Picture = LoadPicture("F:\Finalised reports\Templates\Macros\evolution48.bmp")
Call CreateButtonEvent
End Sub
Sub addref()
On Error Resume Next
Application.VBE.ActiveVBProject.References.AddFromFile "C:\Program Files (x86)\Common Files\Microsoft Shared\VBA\VBA6\VBE6EXT.OLB"
Application.VBE.ActiveVBProject.References.AddFromFile "C:\Program Files\Common Files\Microsoft Shared\VBA\VBA6\VBE6EXT.OLB"
End Sub
Private Sub CreateButtonEvent()
On Error GoTo errtrap
Dim oXl As Application: Set oXl = Application
oXl.EnableEvents = False
oXl.DisplayAlerts = False
oXl.ScreenUpdating = False
oXl.VBE.MainWindow.Visible = False
Dim oWs As Worksheet
Dim oVBproj As VBIDE.VBProject
Dim oVBcomp As VBIDE.VBComponent
Dim oVBmod As VBIDE.CodeModule '
Dim lLine As Single
Const QUOTE As String = """"
Set oWs = Sheets("Contingency")
Set oVBproj = ThisWorkbook.VBProject
Set oVBcomp = oVBproj.VBComponents(oWs.CodeName)
Set oVBmod = oVBcomp.CodeModule
With oVBmod
lLine = .CreateEventProc("Click", "BtnExport") + 1
.InsertLines lLine, "Call CSVFile"
End With
oXl.EnableEvents = True
oXl.DisplayAlerts = True
Exit Sub
errtrap:
End Sub
An easy way to do it:
1 - Insert a class module and write this code:
Public WithEvents ChkEvents As MSForms.CommandButton
Private Sub ChkEvents_click()
MsgBox ("Click Event")
End Sub
2 - Insert a userform and write this code:
Dim Chk As New Clase1
Private Sub UserForm_Initialize()
Dim NewCheck As MSForms.CommandButton
Set NewCheck = Me.Controls.Add("Forms.CommandButton.1")
NewCheck.Caption = "Prueba"
Set Chk.ChkEvents = NewCheck
End Sub
Now show the form and click the button
I think the code needs to be added to the Userform, not to the button itself.
So something like
With UserForm1.CodeModule
'Insert code here
End With
In place of your With ThisWorkbook

Resources