Change font colour of a textbox - vba

I want to open an Excel file, go to the first sheet in the file, and change the text colour of textbox1 to red.
The only way I have managed to do it so far is via recording the macro.
It gives me
Workbooks.Open (fPath & sName)
Sheets(1).Select
ActiveSheet.Shapes.Range(Array("TextBox1")).Select
With Selection.ShapeRange(1).TextFrame2.TextRange.Characters(1, 262).Font.Fill
.Visible = msoTrue
.ForeColor.RGB = RGB(255, 0, 0)
.Transparency = 0
.Solid
End With
That's fine; however the length of the text is variable so I get an error with the code if it is less than the 262 characters above.
I tried to introduce
CharCount = Len(textbox1.Text)
However I get error 424 Object required
I initially tried
Sheets(1).Select
ActiveSheet.TextBox1.ForeColor = RGB(255, 0, 0)
but got error 438 Object doesn't support this property or method.

If you want to change the font colour of the entire textbox (i.e. not just certain characters) then skip the Characters method. Also you shouldn't rely on .Select, ActiveSheet and the likes. Set proper references instead.
This works:
Dim wb As Workbook
Dim ws As Worksheet
Dim s As Shape
Set wb = Workbooks.Open(fPath & sName)
Set ws = wb.Sheets(1)
Set s = ws.Shapes("TextBox 1")
s.TextFrame2.TextRange.Font.Fill.ForeColor.RGB = RGB(255, 0, 0)

try this,
Sub Button2()
Dim sh As Shape
Set sh = Sheets("Sheet1").Shapes("Textbox1")
sh.TextFrame.Characters.Font.Color = vbRed
End Sub

I'm using Excel 2000 (long story) and I conditionally set the color of text box "M_in_out" in "Sheet7" with the following.
Private Sub M_in_out_LostFocus()
Dim sh As Sheet7
Set sh = Sheet7
vx = CInt(M_in_out.Value)
If vx > 0 Then
sh.M_in_out.ForeColor = vbBlack
Else
sh.M_in_out.ForeColor = vbRed
End If
sh.Cells(23, 6).Value = sh.Cells(23, 6).Value + vx
End Sub
You should probably use more meaningful variable names etc!.

Related

VBA code to extract form data from Word to Excel. Suddenly the code not longer works, but there is not error or bug message, why?

I set up the code below several months ago and tested it, and had colleagues test it and it was working fine. I have just opened it and it no longer works, but I am not getting an alert of any error or bug. The macro runs and I can see the relevant cells being formatted (i.e. the final part of the code), but MS Word does not appear to open at any point. I set up a simple "Document.Open" sub to check that Excel was still working with Word, and that was fine. Can anyone help?
N.B. (1) I have redacted the specifics in the following, but have checked that the folder directories and file names are correct.
N.B. (2) I have recently moved from Windows 2010 and the associated Office applications to 365. However, we currently have both system running concurrently and the problem seems to appear on both.
N.B. (3) The code is current a Private Sub attached to an control button, but even when put into a Module it does not work.
N.B. (4) if I Step In with F8 it gets stuck as "wdApp.Quit" and I have to close Excel through Task Manager, but there is still no error alert.
N.B. (5) I removed the instructions to close and quit Word and there does not appear to be any instance of Word open according to task manager.
Please help:-)
Code:
Private Sub REDACTEDTITLE_Click()
Dim wdApp As New Word.Application
Dim myForm As Word.Document
Dim CCtl As Word.ContentControl
Dim myFolder As String, strFile As String
Dim myWorksheet As Worksheet, i As Long, j As Long
myFolder = "R:\REDACTED_FOLDER_PATH"
Application.ScreenUpdating = False
If myFolder = "" Then Exit Sub
Sheets("Data").Select
Set myWorksheet = ActiveSheet
ActiveSheet.Range("B13:CB27").Clear
i = myWorksheet.Cells(13, 2).End(xlUp).Row
strFile = Dir(myFolder & "\*.docx", vbNormal)
While strFile <> ""
i = i + 1
Set myForm = wdApp.Documents.Open(Filename:=myFolder & "\" & strFile, AddToRecentFiles:=False, Visible:=False)
With myForm
j = 1
For Each CCtl In .contentcontrols
j = j + 1
myWorksheet.Cells(i, j) = CCtl.Range.Text
Next
End With
myForm.Close SaveChanges:=False
strFile = Dir()
Wend
wdApp.Quit
Set myForm = Nothing: Set wdApp = Nothing: Set myWorksheet = Nothing
Application.ScreenUpdating = True
Range("B13:CB27").HorizontalAlignment = xlLeft
Range("B13:CB27").VerticalAlignment = xlTop
Range("B13:CB27").WrapText = True
Range("B13:CB27").Interior.Color = RGB(197, 220, 243)
Range("B13:CB27").Borders(xlEdgeBottom).Weight = xlThin
Range("B13:CB27").Borders(xlEdgeLeft).Weight = xlThin
Range("B13:CB27").Borders(xlEdgeRight).Weight = xlThin
Range("B13:CB27").Borders(xlEdgeTop).Weight = xlThin
Range("B13:CB27").Borders(xlInsideHorizontal).Weight = xlThin
Range("B13:CB27").Borders(xlInsideVertical).Weight = xlThin
Range("B13:CB27").Borders(xlEdgeBottom).Color = RGB(255, 255, 255)
Range("B13:CB27").Borders(xlEdgeLeft).Color = RGB(255, 255, 255)
Range("B13:CB27").Borders(xlEdgeRight).Color = RGB(255, 255, 255)
Range("B13:CB27").Borders(xlEdgeTop).Color = RGB(255, 255, 255)
Range("B13:CB27").Borders(xlInsideHorizontal).Color = RGB(255, 255, 255)
Range("B13:CB27").Borders(xlInsideVertical).Color = RGB(255, 255, 255)
End Sub

Modifying shape colour based on cell value

Am looking to modify the shape colour based on a linked cell value ...
The shape is 'test' and the cell value "X11". I'm getting the error that the object does not support this property or method ...
Sub CChange()
Dim ws As Worksheet
Set ws = ThisWorkbook.ActiveSheet
With ws.Shapes.Range(Array("test"))
If .Range("X11") = 1 Then
.Fill.ForeColor.RGB = RGB(18, 38, 43)
ElseIf .Range("X11") = 2 Then
.Fill.ForeColor.RGB = 0
End If
End With
End Sub
Change your code to this , your with statement is wrong.
You are not working with worksheet hence you cannot access range with .Range.
Sub CChange()
Dim ws As Worksheet
Set ws = ThisWorkbook.ActiveSheet
With ws.Shapes.Range(Array("test"))
If ws.Range("X11") = 1 Then
.Fill.ForeColor.RGB = RGB(18, 38, 43)
ElseIf ws.Range("X11") = 2 Then
.Fill.ForeColor.RGB = 0
End If
End With
End Sub

Trying to dynamically update textboxes with values in VBA

I have put a map into excel of a building seating chart and created activeX text boxes on each spot where someone is sitting. I also have a list of each seat and the person sitting there. What I want to do is go through the list and assign the correct name to the textbox for each person. The name of each textbox is "TextBox____" where the blank is the seat name". I am getting an error on the "set tbox" line.
Sub UpdateMap()
Dim name As Variant
Dim tbox As MSForms.TextBox
Dim rng As Range
Dim cell As Range
With ThisWorkbook.Worksheets("5th floor map")
Set rng = .Range("A2:A5")
For Each cell In rng
ws = cell.Value
name = Application.VLookup(ws, .Range("A2:B5"), 2, False)
Set tbox = ThisWorkbook.Worksheets("5th floor map").Shapes("TextBox" & ws)
tbox.Value = name
Next
End With
End Sub
I only used the first four names/seats for this example, and used the for loop because in reality there are over 100 of these. Any suggestions for how i could make this work would be appreciated. Or if I am thinking about this totally wrong, please tell me that too. Thanks.
try this
Sub UpdateMap()
Dim rng As Range
Dim cell As Range
With ThisWorkbook.Worksheets("5th floor map")
Set rng = .Range("A2:A5")
For Each cell In rng
.OLEObjects("TextBox" & cell).Object.Text = cell.Offset(0, 1).Value
Next
End With
End Sub
try this
Sub oo()
Dim ol As OLEObject
Set ol = ThisWorkbook.Worksheets("MySheet").OLEObjects("TextBox1")
With ol
.Object.Text = "blabla"
.Object.ForeColor = RGB(0, 0, 192)
.Object.BorderStyle = fmBorderStyleSingle
.Object.SpecialEffect = fmSpecialEffectFlat
.Object.BackColor = RGB(192, 192, 192)
'.object.....
End With
End Sub

Generating dynamic charts with VBA

I have to create almost 200 charts of time series. So I tried to write a macro that finishes most of the work I need to do.
I generated names for the time series like this as an example:
Name:= AKB_ExampleA
The name refers to a dynamic range which I declared with this formula:
=OFFSET('sheet1'!$C$7:$C$137;0;0;COUNT('sheet1'!$C$7:$C$206))
So now to the macro I coded so far:
Sub graphik_erstellen()
Call graphik1("AKB")
End Sub
Sub graphik(Name As String)
'
Dim Ch As Chart
Dim RngToCover As Range
Set Ch = charts.Add
Set Ch = Ch.Location(Where:=xlLocationAsObject, Name:="Charts")
With Ch
.ChartType = xlLine
.SetSourceData Source:=Range(Name & "_ExampleA")
.SeriesCollection(1).XValues = Range("Datum_Volumen")
.SeriesCollection(1).Name = "SERIES1"
.FullSeriesCollection(1).Select
With Selection.Format.Line
.Visible = msoTrue
.ForeColor.RGB = RGB(192, 0, 0)
.Transparency = 0
End With
.HasTitle = True
.ChartTitle.Text = Name & ", Volumen (nach Korrektur)"
.HasLegend = True
.Legend.Position = xlLegendPositionBottom
.Legend.Select
Selection.Format.TextFrame2.TextRange.Font.Size = 11
Selection.Format.TextFrame2.TextRange.Font.Bold = msoTrue
With .Parent
.top = 100
.left = 100
.height = 287.149606299
.width = 543.685039370078
.Name = Name & "_chart"
End With
End With
End Sub
My problem is, that if I do that, the dynamic range is not really considered. It takes the range of the name (which is $C$7:$C$137) but it should refer to the name itself (in order to be dynamic).
So if I click on the chart to see the series, the series values are declared as: ='sheet1'!$C$7:$C$137 instead of ='sheet1'!ExampleA.
I would be really, really grateful if somebody could help me out.
Best
Elio
I have rearranged a few lines of code and tried to place comments refering to them as well.
Let me know what works. Youjust might need to change SeriesCollection to FullSeriesCollection. Other than that the code works in my Excel 2010.
The first Sub I just get the Range size according to the data available in Column "C" from Row 7.
Let me know.
Option Explicit
Sub graphik_erstellen()
'You always want to use direct reference to a sheet/range chart
'Refering to the WorkBook they are in and the worksheet as well.
'especially if you are opening multiple WorkBooks / Sheets
Dim CurrentWorkSheet As Worksheet
Set CurrentWorkSheet = Workbooks("Book1").Worksheets("Sheet1")
'Dynamically finding the end of the data in Column C
Dim LastRow As Long
LastRow = CurrentWorkSheet.Cells(CurrentWorkSheet.Rows.Count, "C").End(xlUp).Row
'Setting the range using the document reference aswell
Dim AKB As Range
Set AKB = Workbooks("Book1").Worksheets("Sheet1").Range(Cells(7, "C"), Cells(LastRow, "C"))
Call graphik(AKB)
End Sub
Sub graphik(Name As Range)
Dim DataChart As Chart
Dim RngToCover As Range
Set DataChart = Workbooks("Book1").Charts.Add
'With Excel 2010 the line above will automatically add the chart as a sheet and not aobject in a sheet
'Set DataChart = DataChart.Location(Where:=xlLocationAsObject, Name:="Charts")
With DataChart
.Name = "Charts" ' This will be the Name of the CHart Tab
.ChartType = xlLine
.SetSourceData Source:=Name
'You can see below I avoided the Select and Selection
With .SeriesCollection(1)
'Using Offset I just used the data one cell to the left of the range
.XValues = Name.Offset(0, -1)
.Name = "SERIES1"
With .Format.Line
.Visible = msoTrue
.ForeColor.RGB = RGB(192, 0, 0)
.Transparency = 0
End With
End With
.HasTitle = True
.ChartTitle.Text = "MIDDEL TOP TEXT" 'Name & ", Volumen (nach Korrektur)"
.HasLegend = True
With .Legend
.Position = xlLegendPositionBottom
.Format.TextFrame2.TextRange.Font.Size = 11
.Format.TextFrame2.TextRange.Font.Bold = msoTrue
End With
'Not sure about this, it doesnt work in my Excel 2010
'
With .Parent
.Top = 100
.Left = 100
.Height = 287.149606299
.Width = 543.685039370078
.Name = Name & "_chart"
End With
End With
End Sub
Let me know what your intention is for the Sheet and Chart names and then I can help with getting that to what you need as well.

VBA Excel Won't Change Cell to the Right Color

I am new with using VBA macros in excel, and I am trying to change the background color of a cell based on the condition that another cell is not empty. I thought I had it figured out, but I must be doing something wrong, because no matter what color I specify the 'Interior.Color' to change to, it turns the cell an ugly blue color. Here's the code:
Sub Hello()
MsgBox ("Hello, world!")
Dim shSource As Worksheet
Dim shDest As Worksheet
Set shSource = ThisWorkbook.Sheets("Box Channel Tracking")
Set shDest = ThisWorkbook.Sheets("Box Channel Schematic")
If shSource.Range("C176").Value <> "" Then
shDest.Range("E8").Interior.Color = RGB(255, 255, 255)
shDest.Range("E8").Interior.Pattern = xlSolid
Else
shDest.Range("E8").Interior.Color = Red
shDest.Range("E8").Interior.Pattern = xlSolid
End If
End Sub
You've got to use either the color's index or the appropriate RGB value. Change the first line of the else branch to:
shDest.Range("E8").Interior.Color = RGB(255, 0, 0)
Full code sample:
Sub Hello()
MsgBox ("Hello, world!")
Dim shSource As Worksheet
Dim shDest As Worksheet
Set shSource = ThisWorkbook.Sheets("Box Channel Tracking")
Set shDest = ThisWorkbook.Sheets("Box Channel Schematic")
If shSource.Range("C176").Value <> "" Then
shDest.Range("E8").Interior.Color = RGB(255, 255, 255)
shDest.Range("E8").Interior.Pattern = xlSolid
Else
shDest.Range("E8").Interior.Color = RGB(255, 0, 0) '<-modified
shDest.Range("E8").Interior.Pattern = xlSolid
End If
End Sub
Check that the color palette for excel has not been changed
Depending upon your version you can reset it to a standard palette
in 2003 Tools>Options>Color
http://support.microsoft.com/kb/288412 describes how to do this also
Or in a later version you may have a custom theme applied that is causing issues