Insert a TextBox and set the formula - excel

In VBA for Excel 2007, I want to add a textbox to the active sheet and set its formula to a cell. My problem is that the AddTextbox function returns an object with typename Shape, not TextBox, so it does not have a Formula property to set. Instead, I ended up looping through all the textboxes to find the right one, then set its Formula. Is there a better way to do this?
Sub insertTextBoxWithFormula()
Set newTextBox = ActiveSheet.Shapes.AddTextbox(msoTextOrientationHorizontal, 200, 200, 150, 150)
newTextBox.Name = "New TextBox"
'newTextBox.Formula = "=$A$1" 'This is what I wanted to do
'This is what I did instead
For Each CurrentTextBox In ActiveSheet.TextBoxes
If CurrentTextBox.Name = "New TextBox" Then
CurrentTextBox.Formula = "=B3"
CurrentTextBox.Name = "Finished TextBox"
End If
Next CurrentTextBox
End Sub

You can index the TextBoxes collection using the name of the control. So your example can be abbreviated to:
ActiveSheet.Shapes.AddTextbox(msoTextOrientationHorizontal, 200, 200, 150, 150).Name = "New TextBox"
ActiveSheet.TextBoxes("New TextBox").Formula = "=$B$3"

Or this:
Dim newshp As Shape
Dim newtb As TextBox
Set newshp = ActiveSheet.Shapes.AddTextbox _
(msoTextOrientationHorizontal, 200, 200, 150, 150)
Set newtb = newshp.OLEFormat.Object
newtb.Formula = "$A$1"

Related

VBA - Label lose text after paste

So, I'm trying to create "cards" that the user can move around even when the the workbook is locked. Each card will contain info about a certain project.
The way I'm doing it:
Create a few shapes (an rectangle and a few labels and icons)
Group them
Cut the group
Paste as image
The problem is that when I paste as image, all labels loose their text, they change back to "label1".
If I run the code line by line, they don't lose the text.
I've tried already to add "time" between the cut and paste, adding some lines of code, moving the paste line to a separated sub, and even using Application.Wait(), but nothing worked.
I need to have them as an image (or one solid object - just a group doesn't work), because after the macro is finished, the worksheet is locked back again, and there is another macro to allow the user to move shapes even when the workbook is locked.
Here is a sample to show the problem.
Sub MyCode()
Set wkm = Workbooks(ThisWorkbook.Name)
Set wsm = wkm.Worksheets("TestSheet")
'Just two labels as exemple, the original code has more labels, more icons, and the rounded rectangle)
'The values for the constructors in the original code are defined by the user by a forms
Call GenerateLabel("plaseWork", "Name of the project", 14, 30)
Call GenerateLabel("whyCantYouJustWork", "Name of the user", 42, 30)
wsm.Shapes.Range(Array("plaseWork", "whyCantYouJustWork")).Group.Name = "myGroup"
Set freeSlot = wsm.Range("B10") 'Just a random cell, in the original code there is a function to define the position
Application.CutCopyMode = False
wsm.Shapes("myGroup").Cut
With wsm.Pictures.Paste
.left = freeSlot.left
.top = freeSlot.top
End With
Application.CutCopyMode = False
Set card = wsm.Pictures(wsm.Pictures.Count)
card.Name = "card" & projectName
End Sub
Sub GenerateLabel(labelDescription As String, projectName As String, top As Integer, left As Integer)
Set lbLabel = wsm.OLEObjects.Add(ClassType:="Forms.Label.1")
With lbLabel
.Name = labelDescription
.Object.BackStyle = fmBackStyleTransparent
.Width = 160
.top = top
.left = left
End With
With wsm
.OLEObjects(lbLabel.Name).Object.Caption = projectName
.Shapes(lbLabel.Name).Fill.Transparency = 1
End With
End Sub
What about using shapes with no outline or fill, in place of labels?
Sub MyCode()
Dim wsm As Worksheet, arr(0 To 1), grp As Shape
Set wkm = Workbooks(ThisWorkbook.Name)
Set wsm = wkm.Worksheets("TestSheet")
arr(0) = AddLabel(wsm, "Name of the project", 14, 30).Name
arr(1) = AddLabel(wsm, "Name of the user", 42, 30).Name
Set freeSlot = wsm.Range("B10") 'Just a random cell, in the original code there is a function to define the position
wsm.Shapes.Range(arr).Group.Cut
With wsm.Pictures.Paste
.left = freeSlot.left
.top = freeSlot.top
End With
Set card = wsm.Pictures(wsm.Pictures.Count)
card.Name = "card" & projectName
End Sub
'Add a shape to a worksheet, with the text provided.
' Return the added shape
Function AddLabel(ws As Worksheet, projectName As String, top As Integer, left As Integer)
Dim shp
Set shp = ActiveSheet.Shapes.AddShape(msoShapeRectangle, left, top, 160, 30)
With shp
.Fill.Visible = msoFalse
.Line.Visible = msoFalse
With .TextFrame2.TextRange.Characters
.Text = projectName
.Font.Fill.ForeColor.RGB = vbBlack
.Font.Size = 14
End With
End With
Set AddLabel = shp
End Function

Change Event for Multiple Check Boxes // Excel VBA // WithEvents // ClassModule

I have 25 text boxes named in the following manner on a UserForm
Name: id_[X]_box 1<= x <= 25
I am trying to write a program which can register a change event for all 25 boxes and populate the corresponding [DESCRIPTION] Labels.
Naming scheme for Description Labels Name: desc_[X]_label 1 <= X <= 25
When I program for a change event for just one box (i.e id_box_1), the functionality works fine.
When I try to implement for the 25 boxes with WithEvents and ClassModules, I am getting an error "Can't compile Module"
The form's Name: links
Please see relevant code snippets below
Code in the UserForm_Initialize function
Private Sub UserForm_Initialize()
'Code to make single change event subroutine register for all id_[INT]_textboxes on links form
Dim ctrl As MSForms.Control
Dim text_box_handler As text_boxes_change
Set textBox_collection = New Collection
For Each ctrl In Me.controls
If TypeOf ctrl Is MSForms.TextBox Then
If Split(ctrl.Name, "_")(0) = "id" Then
Set text_box_handler = New text_boxes_change
Set text_box_handler.control_text_box = ctrl
textBox_collection.Add text_box_handler
End If
End If
Next ctrl
End Sub
Custom Class Module Code
Class Module Name: text_boxes_change
Option Explicit
'This class assists in validating multiple text boxes on forms without having to define event
functions for each text box separately
'Global Constants
Const CASHFLOW As String = "Chart"
Const SETUP As String = "Settings"
Const INVOICE_STATUSES As String = "K13:K18"
Const TIME_UNITS As String = "L21:L24"
Const RELATION_TYPES As String = "M21:M25"
Const ACTIVITIES_COL As String = "T"
Const PROJ_START_ROW As Integer = 6
Public WithEvents MyTextBox As MSForms.TextBox
Public Property Set control_text_box(ByVal tb As MSForms.TextBox)
Set MyTextBox = tb
End Property
Public Sub BoxesGroup_Change()
'Setting default background color for the box
Me.MyTextBox.BackColor = RGB(255, 255, 255)
'Setting up Cashflow Worksheet Object
Dim cashflow_sheet As Worksheet
Set cashflow_sheet = Sheets("Chart")
'Finding lastrow with text inside the Sub-Activites column in Chart sheet
Dim lastrow As Integer
lastrow = cashflow_sheet.Cells(Rows.Count, ACTIVITIES_COL).End(xlUp).Row
'Range to represent the activities column in Chart worksheet
Dim activities_range As Range
Set activities_range = cashflow_sheet.Range(ACTIVITIES_COL & CStr(PROJ_START_ROW) & ":" & _
ACTIVITIES_COL & CStr(lastrow))
'A variable to store the user inputed value for id_box
Dim row_id As String
row_id = Me.MyTextBox.value
If IsNumeric(row_id) = True Then
If CInt(row_id) >= PROJ_START_ROW And CInt(row_id) <= lastrow Then
Dim desc_caption As String
'SheetFunctions is a Module ; links_description is a Function that returns a string
representing a cell address based on the rules of the workbook; functionality is tested and verified
for this part
desc_caption = SheetFunctions.links_description(row_id)
If desc_caption <> "" Then
Me.MyTextBox.BackColor = RGB(255, 255, 255)
Me.desc_1_label.Caption = desc_caption
Else
Me.MyTextBox.BackColor = RGB(140, 39, 30)
End If
Else
Me.MyTextBox.BackColor = RGB(140, 39, 30)
End If
Else
Me.MyTextBox.BackColor = RGB(140, 39, 30)
End If
End Sub
Screenshot of the Form

How to insert a command button relative to a cell (value)?

I would like a VBA code to put this button lets say two cells (to the right) away from a cell in the sheet called "hello". Here's the command button code:
Set objBtn = ActiveSheet.OLEObjects.Add(ClassType:="Forms.CommandButton.1", Link:=False _
, DisplayAsIcon:=False, Left:=480, Top:=200, Width:=90, Height:= _
30)
objBtn.Name = "button1"
I don't want to use the cell location as reference, instead the cell value which is "hello". So maybe first I want to look for the value and then insert the command button relative to it.
Yes, that's the way to do it, e.g.
Sub x()
Dim objBtn As OLEObject, r As Range
Set r = Cells.Find("hello") 'should specify more parameters than this
If Not r Is Nothing Then
Set objBtn = ActiveSheet.OLEObjects.Add(ClassType:="Forms.CommandButton.1", Link:=False, _
DisplayAsIcon:=False, Left:=r.Offset(, 2).Left, Top:=r.Top, Width:=90, Height:=30)
objBtn.Name = "button1"
End If
End Sub
'You can fixe a button to a specific cell here to cell A1
Dim rngcbn1 As Range
Set rngcbn1 = ActiveSheet.Range("A1")
With ActiveSheet.OLEObjects("CommandButton1")
.Top = rngcbn1.Top
.Left = rngcbn1.Left
.Width = rngcbn1.Width
.Height = rngcbn1.RowHeight
End With

Automatically create and name an Object from a set list

I'm currently trying to auto name the objects from a referenced list rather than just have the object text stated in the script.
How do I get the script to reference a separate worksheet called Process Steps where the text value is in cell C7 instead of entering the statement in the script as Step 1
ActiveSheet.Shapes.AddShape(msoShapeRectangle, 50, 50, 100, 50).Select
Selection.Formula = ""
Selection.ShapeRange.ShapeStyle = msoShapeStylePreset40
Selection.ShapeRange(1).TextFrame2.TextRange.Characters.Text = "Step1"
Peter has already mentioned how to pick up a value from another cell. Taking this a bit ahead.
Please avoid the use of .Select/.Activate INTERESTING READ
Is this what you are trying?
Sub Sample()
Dim shp As Shape
Set shp = ActiveSheet.Shapes.AddShape(msoShapeRectangle, 50, 50, 100, 50)
With shp.OLEFormat.Object
.Formula = ""
.ShapeRange.ShapeStyle = msoShapeStylePreset40
.ShapeRange(1).TextFrame2.TextRange.Characters.Text = _
ThisWorkbook.Sheets("Process Steps").Range("C7").Value
End With
End Sub

VBA excel combobox shapes select

i have problem with selecting combobox after creating it via shapes object. Can someone please help?
My code is
Dim comboBoxRange As Range
Set comboBoxRange = Sheets(axleDataWindowName).Range("F2:F4")
currentSheet.DropDowns.Add(20, 40, 100, 15).Name = "modifiedComboBox"
With currentSheet.Shapes("modifiedComboBox")
.Left = 450
.List comboBoxRange.Value
End With
You need to call currentSheet.Dropdowns("modifiedComboBox") instead of currentSheet.Shapes("modifiedComboBox"). Also use .AddItem instead of .List:
Dim comboBoxRange As Range
Set comboBoxRange = Sheets(axleDataWindowName).Range("F2:F4")
currentSheet.DropDowns.Add(20, 40, 100, 15).Name = "modifiedComboBox"
With currentSheet.Shapes("modifiedComboBox")
.Left = 450
.AddItem comboBoxRange.Value
End With

Resources