Change insert line color with VBA macro - vba

Code below was created (not by me, and saved as *.dotm) in Microsoft Word 97-2003, when default "insert shape/line" was black. Used as procedure template with specific cover page, header, outline style, etc. When the *.doc files are saved to *.docx, and the "SignoffLine" macro is activated, the inserted line's color is blue (MS Word 2010 default for Insert Shape/Line?).
I can change the default color per document, and I can change it via Normal.dotm, but want to edit the macro below so inserted line is always black.
Sub SignoffLine()
On Error GoTo endthis
i = Selection.Information(wdVerticalPositionRelativeToPage)
Set oFFline = ActiveDocument.Shapes.AddLine(554, i + 12, 524, i + 12).Line
With oFFline.Line
.Weight = 0.75
End With
oFFline.Name = "hline" & idi
idi = idi + 1
endthis:
End Sub

It's quite simple... You need to define oFFline object as a Shape and then to set its properties as follow:
Sub SignoffLine()
Dim oFFline As Shape
Dim i As Integer
On Error GoTo endthis
i = Selection.Information(wdVerticalPositionRelativeToPage)
Set oFFline = ActiveDocument.Shapes.AddLine(554, i + 12, 524, i + 12)
With oFFline.Line
.Weight = 0.75
'set black color
.ForeColor.RGB = RGB(0, 0, 0)
End With
oFFline.Name = "hline" & idi
idi = idi + 1
endthis:
Set oFFline = Nothing
End Sub
For further information, please see: Shape Object (Word) and RGB

Related

Type Mismatch Error in Word, but not in Excel or PowerPoint

I'm programming a custom chart add-in for Word that should behave the same as add-ins I've already done for Excel and PowerPoint. The code is very similar in all three programs, but I'm getting a baffling error in Word that doesn't occur in the other 2 programs.
Excel (works just fine):
Sub AddTextboxToChart()
Dim oChart As Chart
Dim oChtShp As Shape
Dim oLegShp As Shape
sChtName = ActiveChart.Name
ChtShpName$ = Right(sChtName, Len(sChtName) - InStrRev(sChtName, " ", Len(ActiveSheet.Name) + 1))
Set oChtShp = ActiveSheet.Shapes(ChtShpName$)
Set oChart = oChtShp.Chart
Set oLegShp = oChart.Shapes.AddTextbox(msoTextOrientationHorizontal, 100, 100, 100, 100)
oLegShp.Fill.ForeColor.RGB = RGB(0, 0, 0)
End Sub
PowerPoint (also works fine):
Sub AddTextboxToChart()
Dim oChart As Chart
Dim oChtShp As Shape
Dim oLegShp As Shape
If ActiveWindow.Selection.ShapeRange(1).HasChart Then
Set oChtShp = ActiveWindow.Selection.ShapeRange(1)
Set oChart = oChtShp.Chart
Set oLegShp = oChart.Shapes.AddTextbox(msoTextOrientationHorizontal, 100, 100, 100, 100)
oLegShp.Fill.ForeColor.RGB = RGB(0, 0, 0)
End If
End Sub
Word (errors on "Set oLegShp" line):
Sub AddTextboxToChart()
Dim oChart As Chart
Dim oChtShp As Shape
Dim oLegShp As Shape
If ActiveWindow.Selection.ShapeRange(1).HasChart Then
Set oChtShp = ActiveWindow.Selection.ShapeRange(1)
Set oChart = oChtShp.Chart
Set oLegShp = oChart.Shapes.AddTextbox(msoTextOrientationHorizontal, 100, 100, 100, 100) 'This line errors with Type Mismatch
oLegShp.Fill.ForeColor.RGB = RGB(0, 0, 0)
End If
End Sub
Excel and PowerPoint behave as expected, but Word errors out with a Type Mismatch when it tries to set the shape reference to an added text box. Any ideas or workarounds?
If you try to run the code, create a sample chart in Word, then set it to be floating in front of the text. Otherwise, Word sees it as an Inline Shape, which is a whole other can of worms.
I'm running Version 2205 (Build 15225.20288 Click-to-Run) under Windows 10.
(Edit) A kludge to get around the bug:
oChart.Shapes.AddTextbox msoTextOrientationHorizontal, 100, 100, 100, 100
For x = 1 To oChart.Shapes.Count
If oChart.Shapes(x).Left = LegLeft And oChart.Shapes(x).Top = LegTop Then
oChart.Shapes(x).Fill.ForeColor.RGB = RGB(0,0,0)
End If
Next x

How do I select format an active selection of words in a textbox

I'm trying to explore how do I apply some formatting to only few selected words in a textbox but so far unable to accomplish this myself.
Somehow with the code I created below, I can only use it to select all the words in the textbox instead of just a few words I want.
It would be great if anyone can provide me a simpler/ existing codes that can help me solve this please ?
Thanks in advance
Sub ActiveTextRange()
Dim sld As slide
Dim sh As Shape
Dim wordcount As Long, j As Long, x As Long, y As Long, z As Long
wordcount = ActiveWindow.Selection.ShapeRange(1).textFrame.TextRange.Words.Count
With ActiveWindow.Selection.ShapeRange(1)
.textFrame.TextRange.Words(Start:=1, Length:=wordcount).Font.Color.RGB = RGB(230, 0, 0)
End With
End Sub
The following might help. Key to this is being able to track the location of the specific text you want to change in amongst larger chunks of text; my suggestion is to format each bit of text as you add it to the shape. Cheers.
Option Explicit
Sub ActiveTextRange()
Dim vPresentation As presentation
Dim vSlide As Slide
Dim vShape As Shape
Dim vAddThisText As String
' Create a new presentation, add a slide and a rectangle shape
Set vPresentation = Application.Presentations.Add
Set vSlide = vPresentation.Slides.Add(vPresentation.Slides.Count + 1, ppLayoutBlank)
Set vShape = vSlide.Shapes.AddShape(msoShapeRectangle, 10, 10, 600, 300)
' Make the shape white with a 3pt dark red border
vShape.Fill.ForeColor.RGB = rgbWhite
With vShape.Line
.ForeColor.RGB = rgbDarkRed
.Weight = 3
End With
' Setup the shape to be left aligned, font color, top anchored, etc
With vShape.TextFrame
.TextRange.Paragraphs.ParagraphFormat.Alignment = ppAlignCenter
.TextRange.Font.Color.RGB = rgbBlack
.VerticalAnchor = msoAnchorMiddle
.TextRange.ParagraphFormat.SpaceAfter = 6
.TextRange.ParagraphFormat.WordWrap = msoCTrue
End With
' And now format the word red, which is the 7th character and is 3 long
vAddThisText = "Hello Red World"
vShape.TextFrame.TextRange.InsertAfter vAddThisText
With vShape.TextFrame.TextRange.Characters(7, 3)
.Font.Color.RGB = rgbRed
' and change other attributes if needed etc
End With
End Sub
And the output is ...
This colors the second and third words red in a Title placeholder. After Words, the first number is the starting position and the second number is the length:
Sub ColorWords()
Dim objSlide As Slide
Dim objShape As Shape
For Each objSlide In ActivePresentation.Slides
For Each objShape In objSlide.Shapes
If objShape.Type = msoPlaceholder Then
If objShape.PlaceholderFormat.Type = ppPlaceholderTitle Or objShape.PlaceholderFormat.Type = ppPlaceholderCenterTitle Then
With objShape.TextFrame2.TextRange.Words(2, 2).Font.Fill
.Solid
.ForeColor.RGB = RGB(255, 0, 0)
End With
End If
End If
Next objShape
Next objSlide
End Sub
To color a word selection, use:
ActiveWindow.Selection.TextRange.Font.Color.RGB = RGB(Red:=255, Green:=0, Blue:=0)
OK. I think I better understand the ask ... but I'm assuming in this response you're selecting text ... rather than just a shape itself. So you're editing the powerpoint, select some text in a shape, and want to run a macro to format(?) It should be as simple as creating the following in a code module (and then I created a custom access toolbar link to run the macro at the top of PowerPoint to make it quick):
Option Explicit
Sub ActiveTextRange()
ActiveWindow.Selection.TextRange.Font.Color.RGB = rgbRed
End Sub
Before:
Select the text "Red" and run macro:
Btw ... if you want to select just the shape and have some logic choose the text, the concept is a mix of this and my first answer.

Excel VBA - color data labels ("value from cells") according to the font of the source

I have to run many bar charts in excel 2016, each one showing the company performance over the seasons, for a certain country. On top of each bar I'd like to see the %Change in this format [Color10]0%"▲";[Red] -0%"▼". Reason why I added the data labels, and I used the function "value from cells" to show the %Change instead of the amount sold. Now everything is in place, and my percentages are nicely placed on top of the bars, but no way I can color them automatically (positive green and negative red). I tried formatting the labels directly from the format window placed under "numbers", but I discovered it doesn't work at all when the label content is derived using "value from cells".
So I started looking into VBA, but since I'm pretty ignorant about programming, I didn't succeed. I'm looking for a code that changes the data labels of my chart so that they maintain the font of the source (in the source my %Change values are already in the desired format ([Color10]0%"▲";[Red] -0%"▼"). Googling I found different solutions but none worked. I'll post the ones I that look better to me.
Sub legend_color()
Dim SRS As Series
With ActiveChart
For Each SRS In .SeriesCollection
SRS.ApplyDataLabels AutoText:=True, LegendKey:= _False,
ShowSeriesName:=False,
ShowCategoryName:=False,
ShowValue:=True, _ ShowPercentage:=False,
ShowBubbleSize:=False
SRS.DataLabels.Font.ColorIndex = SRS.Border.ColorIndex
Next SRS
End With
End Sub
This one was the only one that actually run, and colored my labels all white. With the following I run into errors.
Sub color_labels()
Dim chartIterator As Integer,
pointIterator As Integer, _seriesArray() As Variant
For chartIterator = 1 To ActiveSheet.ChartObjects.Count
seriesArray=ActiveWorkbook.Sheets("Sheet1").ChartObjects(chartIterator). _Chart.SeriesCollection(1).Values For pointIterator = 1 To UBound(seriesArray)
If seriesArray(pointIterator) >= 0 Then
ActiveWorkbook.Sheets("Sheet1").ChartObjects(chartIterator). _
Chart.SeriesCollection(1).Points(pointIterator).Interior.Color = _RGB(146, 208, 80)
Else
ActiveWorkbook.Sheets("Sheet1").ChartObjects(chartIterator). _Chart.SeriesCollection(1).Points(pointIterator).Interior.Color = _RGB(255, 0, 0)
End If
Next pointIterator
Next chartIterator
End Sub
Sub ArrowColour()
Dim ncars As Integer
ncars = Range("A1").Value
With ActiveSheet.Shapes.Range(Array("Down Arrow 1")).Fill
If ncars > 0 Then
.ForeColor.RGB = RGB(0, 176, 80)
Else
.ForeColor.RGB = RGB(255, 0, 0)
End If
End With
End Sub
Option Explicit
Sub ApplyCustomLabels()
Dim rLabels As Range
Dim rCell As Range
Dim oSeries As Series
Dim Cnt As Integer
Set rLabels = Range("C2:C" & Cells(Rows.Count, "C").End(xlUp).Row)
Set oSeries = ActiveSheet.ChartObjects(1).Chart.SeriesCollection(1)
oSeries.HasDataLabels = True
Cnt = 1
For Each rCell In rLabels
With oSeries.Points(Cnt).DataLabel.Text = rCell.Value.Font.Color =rCell.Font.Color
End With
Cnt = Cnt + 1
Next rCell
End Sub
Thank you very much in advance for all of your help,
Tommaso
If you're just missing the colors then you can format each label using something like:
Sub Tester()
Dim s As Series, dl As DataLabels, d As DataLabel
Dim i As Long, rngLabels
Set s = ActiveSheet.ChartObjects(1).Chart.SeriesCollection(1)
Set dl = s.DataLabels
'Option 1: set label color based on label value
For i = 1 To dl.Count
With dl(i)
.Font.Color = IIf(Val(.Text) < 0, vbRed, vbGreen)
End With
Next i
'Option 2: set label color based on label source cell
' Note use of DisplayFormat to pick up custom
' formatting colors
Set rngLabels = Range("C7:C13")'<< source range for data labels
For i = 1 To dl.Count
dl(i).Font.Color = rngLabels(i).DisplayFormat.Font.Color
Next i
End Sub

Resizing a Visio shape through Visual Basic

So I've been working on trying to resize a Visio box in Visual Basic for a project in work, using some code that was given to me as I am very new to Visual Basic.
I have tried many methods without any result, and I am now working on using the Shape.Resize() method which works but then throws an error:
If ActiveCell.Offset(0, 2).Value = "D" Then
Dim sizer As Double
sizer# = 2
iData = iData + 1
Set shp = CreateVisioObject(AppVisio, "Box", 2.5, 7.25, ActiveCell.Offset(0, 1).Value, """AccentColor4""")
Set shp = shp.Resize(0, sizer, 65)
Set shp = shp.Resize(2, sizer, 65)
End If
On line 6, I get the error "Run-time error '13': Type mismatch", but the code still executes before throwing this error (ie; the width of the shape changes but the code stops at this line.) Here is the code for the CreateVisioObject:
Function CreateVisioObject(ByRef oVisio As Object, strType As String, posX As Double, posY As Double, strText As String, strColor As String) As Object
Set shp = oVisio.ActiveWindow.Page.Drop(oVisio.Documents.Item("BLOCK_U.VSS").Masters.ItemU(strType), posX, posY)
shp.CellsSRC(visSectionCharacter, 0, visCharacterSize).FormulaU = "20 pt"
Set oCharacters = shp.Characters
oCharacters.Begin = 0
oCharacters.End = Len(oCharacters)
sChar = strText
oCharacters.Text = sChar
shp.CellsSRC(visSectionObject, visRowFill, visFillForegnd).FormulaU = "THEMEGUARD(THEMEVAL(" + strColor + "))"
shp.CellsSRC(visSectionObject, visRowFill, visFillBkgnd).FormulaU = "THEMEGUARD(SHADE(FillForegnd,LUMDIFF(THEMEVAL(""FillColor""),THEMEVAL(""FillColor2""))))"
shp.CellsSRC(visSectionObject, visRowGradientProperties, visFillGradientEnabled).FormulaU = "FALSE"
Set CreateVisioObject = shp
End Function
Here is the reference for the Shape.Resize() - https://msdn.microsoft.com/en-us/vba/visio-vba/articles/shape-resize-method-visio
Also, the code is using an Excel sheet to generate the Visio document.
Thank you for your help!
I didn't know about Shape.Resize Method before. When i want resize some shape i just change it Width and Height
shp.Cells("width") = 2
shp.Cells("height") = 2

VBA not copying whole chart into PowerPoint

I'm dealing with an issue where my VBA code somehow chooses not to include the whole chart when copying to a powerpoint slide. I have the following code:
This code creates my Doughnut chart from 2 numbers.
Function CreateTwoValuesPie(ByVal X As Long, ByVal Y As Long) As Chart
'Returnerer
Set CreateTwoValuesPie = charts.Add
CreateTwoValuesPie.ChartType = XlChartType.xlDoughnut
With CreateTwoValuesPie.SeriesCollection.NewSeries
.Values = Array(X, Y)
End With
With CreateTwoValuesPie
.ChartArea.Format.Fill.Visible = msoFalse
.ChartArea.Format.Line.Visible = msoFalse
.Legend.Delete
.ChartGroups(1).DoughnutHoleSize = 70
With .SeriesCollection(1)
.Points(1).Format.Fill.ForeColor.RGB = RGB(255, 158, 77) 'Score Orange
.Points(2).Format.Fill.ForeColor.RGB = RGB(175, 171, 170) '10 - Score Grå
.Format.Line.ForeColor.RGB = RGB(255, 255, 255)
End With
End With
End Function
This code store the different object and numbers:
Set oPPTApp = CreateObject("PowerPoint.Application")
Set oPPTFile = oPPTApp.Presentations.Open(PP)
Set oPPTShape10 = oPPTFile.Slides(1)
d11 = Format(Dashboard.EAScore1.Caption, "Standard")
Set ch1 = CreateTwoValuesPie(d11, 10 - d11)
ch1.CopyPicture Appearance:=xlScreen, Size:=xlScreen, Format:=xlPicture
With oPPTShape10.Shapes.Paste
.Top = 127
.Width = 177
.Left = 393
End With
The code works fine and creates the correct chart from the number (d11, 10-d11) but when I copy the figure and insert it into my powerpoint slide oPPTShape10 it only copy part of the chart.
This can be seen in the image below:
The correct should've look like the one in the image below:
It worked some days ago and I haven't changed anything since then? Does anyone know how I can make it show the whole figure instead of only the topleft corner of it?