For Loop and If statement. How to combine in one statement - vb.net

I have the following for loop on my project:
'Range and Range Array variables
Dim rngArray As Object
Dim rngArrayMain(0 To 9) As Excel.Range
rngArrayMain(0) = xlWSEE.Range("I40")
rngArrayMain(3) = xlWSEE.Range("V46")
rngArrayMain(4) = xlWSEE.Range("L48:N48")
rngArrayMain(5) = xlWSEE.Range("L51")
rngArrayMain(6) = xlWSEE.Range("J35")
rngArrayMain(7) = xlWSEE.Range("J53")
rngArrayMain(1) = xlWSEE.Range("B57:B61")
rngArrayMain(2) = xlWSEE.Range("B70")
rngArrayMain(8) = xlWSEE.Range("L47")
rngArrayMain(9) = xlWSEE.Range("O47")
For Each rngArray In rngArrayMain
With rngArray
.Font.Bold = True
.Font.Size = 10
.Font.Name = "Calibri"
.Font.ColorIndex = 2 'white
End With
Next rngArray
No problem, works well. However, I have to separate the last two elements of my array because the Font.ColorIndex = 1 for them.
So basically my for loop would be:
if array 0-7
perform this action
if array 8-9
then perform this action.
How can I fix my code to reflect this change? If the question seems elementary it's because I have not been programming long and what I know is self-taught (google, bing, and a few books).
Thanks.

Use a For loop instead of a For Each, like this:
For i As Integer = 0 To rngArrayMain.Length - 1
' First seven items do this (index 0 to 6)
If i <= 6 Then
With rngArrayMain(i)
.Font.Bold = True
.Font.Size = 10
.Font.Name = "Calibri"
.Font.ColorIndex = 2 'white
End With
Else
' Last two items do this
With rngArrayMain(i)
.Font.Bold = True
.Font.Size = 10
.Font.Name = "Calibri"
.Font.ColorIndex = 1
End With
End If
Next
Note: If you remove the With block, then you would actually save lines of code, because you put the If logic around the one property that is different, like this:
For i As Integer = 0 To rngArrayMain.Length - 1
rngArrayMain(i).Font.Bold = True
rngArrayMain(i).Font.Size = 10
rngArrayMain(i).Font.Name = "Calibri"
If i <= 6 Then
rngArrayMain(i).Font.ColorIndex = 2
Else
rngArrayMain(i).Font.ColorIndex = 1
End If
Next

Dim cellsWithColor2 As Range
Dim cellsWithColor1 As Range
Dim xlWSEE As Worksheet
Set xlWSEE = Worksheets("FillTheNameHere")
Set cellsWithColor2 = Application.Union( _
xlWSEE.Range("I40"), _
xlWSEE.Range("V46"), _
xlWSEE.Range("L48:N48"), _
xlWSEE.Range("L51"), _
xlWSEE.Range("J35"), _
xlWSEE.Range("J53"), _
xlWSEE.Range("B57:B61"), _
xlWSEE.Range("B70"))
With cellsWithColor2
.Font.Bold = True
.Font.Size = 10
.Font.Name = "Calibri"
.Font.ColorIndex = 2 'white
End With
Set cellsWithColor1 = Application.Union( _
xlWSEE.Range("L47"), _
xlWSEE.Range("O47"))
With cellsWithColor1
.Font.Bold = True
.Font.Size = 10
.Font.Name = "Calibri"
.Font.ColorIndex = 1 'another color
End With

Related

Setting line on XY scatter without having a marker line

So I am trying to format a XY scatter chart in Excel using VBA and I would like to have lines connecting the markers, but for both the markers and the marker lines I would like for them to be invisible.
For some reason both the marker line and the line that connects the markers both use the same code to change their visibility property.
chart.SeriesCollection(1).Format.Line.Visible = msoFalse
I can change the colours independently using the MarkerBackGroundColor property, but I can't seem to figure out how to make one visible without making the other visible as well.
Any help on this would be very much appreciated.
You can use
FullSeriesCollection(1).Border.LineStyle = xlNone
or
FullSeriesCollection(1).Border.LineStyle = xlSolid
to format the line only.
The code seems to set point. Bellow code is sample of setting points.
Sub ScatterChart_setPoint()
Dim Ws As Worksheet
Dim DB As Range, myCell As Range
Dim Ch As Chart
Dim i As Integer, n As Long, r As Integer, g As Integer, b As Integer
Dim vX(), vY(), vLable(), vMarker
Dim pnt As Point
Dim Shp As Shape
Dim h As Single, w As Single, l As Single, t As Single, fs As Single
Application.DisplayAlerts = False
Set Ws = ActiveSheet 'Sheets("Current Account")
Ws.Activate
Ws.Range("a65536").Select
vMarker = Array(xlMarkerStyleCircle, xlMarkerStyleDash, xlMarkerStyleDiamond, xlMarkerStyleDot, _
xlMarkerStylePlus, xlMarkerStyleSquare, xlMarkerStyleStar, _
xlMarkerStyleTriangle, xlMarkerStyleX)
Set DB = Ws.Range("h3", Ws.Range("h3").End(xlDown)) '<~~ range of data
For Each myCell In DB
If myCell = 0 Or myCell.Offset(, 10) = "" Then
Else
n = n + 1
ReDim Preserve vX(1 To n)
ReDim Preserve vY(1 To n)
ReDim Preserve vLable(1 To n)
vX(n) = myCell
vY(n) = myCell.Offset(, 10)
vLable(n) = myCell.Offset(, -7)
End If
Next myCell
Charts.Add
With ActiveChart
.HasTitle = True
.ChartType = xlXYScatter
.Legend.Position = xlLegendPositionRight
With .ChartTitle
.Characters.Text = Ws.Range("a1").Value
.Characters.Font.Size = 12
End With
.SeriesCollection.NewSeries
With .SeriesCollection(1)
.Name = "OECD"
.XValues = vX
.Values = vY
.Trendlines.Add
With .Trendlines(1)
.DisplayRSquared = True
.DisplayEquation = True
End With
End With
.Axes(xlValue, xlPrimary).HasTitle = True
.Axes(xlValue, xlPrimary).AxisTitle.Characters.Text = Ws.Range("r2")
.Axes(xlCategory, xlPrimary).HasTitle = True
.Axes(xlCategory, xlPrimary).AxisTitle.Characters.Text = Ws.Range("h2")
For i = 1 To n
Set pnt = .SeriesCollection(1).Points(i)
With pnt
.ApplyDataLabels
.DataLabel.Text = vLable(i)
.DataLabel.ShowValue = False
.DataLabel.ShowCategoryName = True
.MarkerStyle = vMarker(WorksheetFunction.RandBetween(0, 8))
With WorksheetFunction
r = .RandBetween(0, 240)
g = .RandBetween(0, 240)
b = .RandBetween(0, 240)
End With
.MarkerForegroundColor = RGB(r, g, b)
.MarkerBackgroundColor = RGB(r, g, b)
End With
.ApplyDataLabels
Next i
Application.DisplayAlerts = True
End Sub

Excel VBA value dynamicly named textboxes

Bottom Line Fix: Changing my dynamicly named textbox to have a _ separator between the column and row to get rid of the ambiguity of the names.
Previous Code:
Set cCntrl = PickTicketForm.Controls.Add("Forms.TextBox.1", "PalletNumber" & i & r, True)
Fix:
Set cCntrl = PickTicketForm.Controls.Add("Forms.TextBox.1", "PalletNumber" & i & "_" & r, True)
I have a userform and it has 15 text boxes columns by X rows (dynamic).
The user inputs numbers into the text boxes. Then I want them to hit a Print button on the user form to run the PrintLabel() sub and put those values into a spreadsheet vertically (B24:Bxx). Then have it print out the spreadsheet and return to the userform.
My issue is I can't seem to get the values from the textboxes.
The textbox names are in an multi-dimensional array style format:
PalletNumber & "row" & "column"
So the first row would be PalletNumber0_0 through PalletNumber0_15. The next row will be PalletNumber1_0 to PalletNumber1_15.
Update:
The user enters the value "1234" into a textbox and clicks "Look Up" to run lookup(). This then searches a spreadsheet for the number and gets all the rows that match and puts them into the userform.
Here is the code snippet
For Each c In Worksheets("Sheet1").range("A2:A" & iRowCount)
If c.value = OrderNumber Then
ReDim Preserve aGetData(6, i)
For a = 0 To 6 'Change this for total of columns Our first index will hold each col of data that is why
'it is set to 0 (arrays start at a base of zero, so
'0,1,2,3,4,5 will be each col(A,B,C).
aGetData(a, i) = c.Offset(0, a) 'This gets each value from col A,B and C
Next a
'Get the data and set it into variables.
ItemNumber = aGetData(5, i)
ItemQty = aGetData(2, i)
'Create "ItemQuantity" text box.
Set cCntrl = PickTicketForm.Controls.Add("Forms.Label.1", "ItemQuantity" & i, True)
With cCntrl
.Caption = ItemQty
.Width = 85
.Height = 18
.Top = 86 + (i * 20)
.Left = 40
.TextAlign = 1 'Left
.Font.Name = "Arial Black"
.Font.Size = "10"
.BackColor = BackgroundColor
End With
'Create "ItemNumber" box
Set cCntrl = PickTicketForm.Controls.Add("Forms.Label.1", "ItemNumber" & i, True)
With cCntrl
.Caption = ItemNumber
.Width = 340
.Height = 18
.Top = 86 + (i * 20)
.Left = 86
.TextAlign = 1 'Left
.Font.Name = "Arial Black"
.Font.Size = "10"
.BackColor = BackgroundColor
End With
'Create each inputbox for the pallets.
For r = 0 To 14
Set cCntrl = PickTicketForm.Controls.Add("Forms.TextBox.1", "PalletNumber" & i & "_" & r, True)
With cCntrl
.Width = 28
.Height = 18
.Top = 86 + (i * 20)
.Left = 354 + (r * 30)
.TextAlign = 1 'Left
.Font.Name = "Arial Black"
.Font.Size = "10"
.BackColor = BackgroundColor
.Text = i & r
End With
Next r
i = i + 1 'Increment for array in case we find another order number
'Our second index "aGetData(index1,index2) is being resized
'this represents each order number found on the sheet
LineCount = LineCount + 1
'Set the scroll bar height for the final form.
ScrollBarHeight = 150 + (i * 20)
End If
Next c
Here is that code snippet:
'Loop through first column completely ( 0 - 5 to test)
' i = 0 means go through every box in column 0 first
For i = 0 To 5
'Loop through rows.
For r = 0 To 2 '( 0 - 2 rows to test)
ActiveCell.Offset(i, 0).value = PickTicketForm.Controls("PalletNumber" & i & r).Text
Next r
Next i
Here is the userform layout:
The spreadsheet output should look like this:
You should add your controls within a For i = 0 To 5 loop as well.
If it remains empty you are adding PalletNumber0, PalletNumber1, PalletNumber2 etc. while you are searching for PalletNumber00, PalletNumber01, PalletNumber02 etc.

Show columns placed in multiple ranges

I have multiple Excel files with the following structure:
Each file has the exact same columns (Apples, Oranges, Bananas, etc.) but placed under different letters throughout the sheets. For example, column "Apples" is under letter A in the first 5 sheets, but it's under letter C in the rest of the sheets. This order is not consistent and varies in each file.
I would like a macro capable of:
Unwrap all the cells in all sheets.
Hide columns from A to Z in all sheets.
Unhide only three columns featuring the words "apples/apple", "oranges/orange" and "bananas/bananas" in row 1.
Shrink to fit the text in the "apples/apple" column and set the width to 120.
Wrap to fit the text on the "oranges/orange" and "bananas/bananas" columns and set the width to 350.
Zoom all sheets to 100%.
I have this macro that works like a charm, as it allows me to choose which three columns I want to keep. However, it works exclusively if they are placed in the exact same order in all sheets:
Sub AdjustTF()
ColumnWidth = 10
ActiveWindow.Zoom = 100
Dim wsh As Worksheet
Dim rng As Range
Dim i As Long
Dim f As Boolean
Dim c As Long
On Error GoTo ErrHandler
' The following two lines are optional
Worksheets(1).Select
Range("A1").Select
For Each wsh In Worksheets
wsh.Cells.WrapText = False
wsh.Cells.VerticalAlignment = xlBottom
wsh.Cells.HorizontalAlignment = xlLeft
wsh.Cells.EntireColumn.Hidden = False
If f = False Then
Set rng = Application.InputBox( _
Prompt:="Select the columns to keep.", _
Type:=8).EntireColumn
f = True
End If
Set rng = wsh.Range(rng.Address).EntireColumn
c = wsh.Cells.Find(What:="*", SearchOrder:=xlByColumns, _
SearchDirection:=xlPrevious).Column
wsh.Range(wsh.Cells(1, 1), wsh.Cells(1, c)).EntireColumn.Hidden = True
With rng
.Hidden = False
With .Areas(1)
.ColumnWidth = 3
For i = 1 To 3
.ColumnWidth = 120 / .Width * .ColumnWidth
Next i
.ShrinkToFit = True
End With
With .Areas(2)
.ColumnWidth = 8
For i = 1 To 3
.ColumnWidth = 350 / .Width * .ColumnWidth
Next i
.WrapText = True
End With
With .Areas(3)
.ColumnWidth = 8
For i = 1 To 3
.ColumnWidth = 350 / .Width * .ColumnWidth
Next i
.WrapText = True
End With
End With
wsh.Cells.EntireRow.AutoFit
NextSheet:
Next wsh
Application.Goto Worksheets(1).Range("A1"), True
Exit Sub
ErrHandler:
Select Case Err
Case 424 ' Object required
Resume NextSheet
Case Else
MsgBox Err.Description, vbExclamation
End Select
End Sub
EDIT: I've also this code, which is significantly lighter (even though doesn't quite perform all tasks I wanted) but for some reasons works only with a single file and not when assigned to my Personal.xls sheet.
Sub AdjustTFAlternate()
Dim R As Range
Dim Ws As Worksheet
Dim Item
'In each worksheet
For Each Ws In ActiveWorkbook.Worksheets
'Hide all columns
Ws.UsedRange.EntireColumn.Hidden = True
'Search for this words
For Each Item In Array("apple*", "orange*", "banana*")
'Search for a keyword in the 1st row
Set R = Ws.Rows(1).Find(Item, LookIn:=xlFormulas, LookAt:=xlWhole)
If R Is Nothing Then
'Not found
Exit For
End If
'Unhide this column
R.EntireColumn.Hidden = False
Next
Next
End Sub
If you simply want a popup box for the user to select the 3 columns on each sheet, remove the line that reads
f = True
that is inside the If f = False Then statement.
If you want the macro to "remember" the column headers for each column chosen on the first page, then you'll need to modify the code slightly (and make some assumptions):
Assumptions
The column headers are in the first row
The column headers are unique (i.e., you don't have the same column title multiple times in the same sheet).
EDIT:
Code will now store all selected columns in an array that will search on each worksheet. For example, if on worksheet 1 you have apple, banana, and coconut, you will get an initial InputBox. If on worksheet 3, you now have apples, bananas, and coconuts, then you will get a second InputBox asking for these values. Now, on worksheets 4-n, the code will search for either apple or apples.
Code
Sub AdjustTF()
ColumnWidth = 10
Dim wsh As Worksheet
Dim rng As Range
Dim i As Long
Dim f As Boolean
Dim c As Long
'Dim aCol(1 To 1, 1 To 3) As String
Dim aCol() As String
ReDim aCol(1 To 3, 1 To 1)
Dim iCol(1 To 3) As Integer
Dim iTemp As Integer
Dim uStr As String
On Error GoTo ErrHandler
' The following two lines are optional
Worksheets(1).Select
Range("A1").Select
For Each wsh In Worksheets
d = 1
wsh.Cells.WrapText = False
wsh.Cells.VerticalAlignment = xlBottom
wsh.Cells.HorizontalAlignment = xlLeft
wsh.Cells.EntireColumn.Hidden = False
If f = False Then
On Error Resume Next
Err.Number = 0
Set rng = Application.InputBox( _
Prompt:="Select the columns to keep.", _
Type:=8).EntireColumn
If Err.Number > 0 Then
Exit Sub
End If
On Error GoTo ErrHandler
f = True
aCol(1, 1) = wsh.Cells(1, rng.Areas(1).Column).Value
aCol(2, 1) = wsh.Cells(1, rng.Areas(2).Column).Value
aCol(3, 1) = wsh.Cells(1, rng.Areas(3).Column).Value
Else
On Error Resume Next
For a = 1 To 3
iCol(a) = 0
Next
For a = 1 To UBound(aCol, 2)
Err.Number = 0
iTemp = wsh.Cells.Find(what:=aCol(1, a), lookat:=xlWhole).Column
If Err.Number = 0 And iCol(1) = 0 Then iCol(1) = iTemp
Err.Number = 0
iTemp = wsh.Cells.Find(what:=aCol(2, a), lookat:=xlWhole).Column
If Err.Number = 0 And iCol(2) = 0 Then iCol(2) = iTemp
Err.Number = 0
iTemp = wsh.Cells.Find(what:=aCol(3, a), lookat:=xlWhole).Column
If Err.Number = 0 And iCol(3) = 0 Then iCol(3) = iTemp
If iCol(1) > 0 And iCol(2) > 0 And iCol(3) > 0 Then Exit For
Next
If iCol(1) = 0 Or iCol(2) = 0 Or iCol(3) = 0 Then
wsh.Activate
Err.Number = 0
Set rng = Application.InputBox( _
Prompt:="Select the columns to keep.", _
Type:=8).EntireColumn
If Err.Number > 0 Then
Exit Sub
End If
a = UBound(aCol, 2) + 1
ReDim Preserve aCol(1 To 3, 1 To a)
aCol(1, a) = wsh.Cells(1, rng.Areas(1).Column).Value
aCol(2, a) = wsh.Cells(1, rng.Areas(2).Column).Value
aCol(3, a) = wsh.Cells(1, rng.Areas(3).Column).Value
Else
uStr = Range(wsh.Cells(1, iCol(1)), wsh.Cells(1, iCol(1))).Address & "," & _
Range(wsh.Cells(1, iCol(2)), wsh.Cells(1, iCol(2))).Address & "," & _
Range(wsh.Cells(1, iCol(3)), wsh.Cells(1, iCol(3))).Address
Set rng = Range(uStr)
End If
On Error GoTo ErrHandler
End If
Set rng = wsh.Range(rng.Address).EntireColumn
c = wsh.Cells.Find(what:="*", SearchOrder:=xlByColumns, _
SearchDirection:=xlPrevious).Column
wsh.Range(wsh.Cells(1, 1), wsh.Cells(1, c)).EntireColumn.Hidden = True
With rng
.Hidden = False
With .Areas(1)
.ColumnWidth = 3
For i = 1 To 3
.ColumnWidth = 120 / .Width * .ColumnWidth
Next i
.ShrinkToFit = True
End With
With .Areas(2)
.ColumnWidth = 8
For i = 1 To 3
.ColumnWidth = 350 / .Width * .ColumnWidth
Next i
.WrapText = True
End With
With .Areas(3)
.ColumnWidth = 8
For i = 1 To 3
.ColumnWidth = 350 / .Width * .ColumnWidth
Next i
.WrapText = True
End With
End With
wsh.Cells.EntireRow.AutoFit
wsh.Activate
ActiveWindow.Zoom = 100
wsh.Cells(1, 1).Select
NextSheet:
Next wsh
Application.Goto Worksheets(1).Range("A1"), True
Exit Sub
ErrHandler:
Select Case Err
Case 424 ' Object required
Resume NextSheet
Case Else
MsgBox Err.Description, vbExclamation
End Select
End Sub

Automatic plotting of graphs from different sheet

I am programming an excel application that takes info from a Tables Sheet ( that it is also programmed and the length and position of each table can change) and generate a graphic for each table in other sheet, called Estimation Sheet, when a button is press.
I managed to do this task for the first graphich (corresponding to first table) but when I try to use the same method for the second...it doesn't work. This is the method used to draw the first graphic:
Public Sub generateGraphicsC(RowResistiveC As Integer)
Dim FirstRow As Integer, FirstColumn As Integer, LastRow As Integer, LastColumn As Integer, GraphLocation As Integer
Dim XelementsC As Integer, Yelements As Integer
Dim myChtObj As ChartObject
Dim rngChtData As Range
Dim rngChtXVal As Range
Dim i As Integer
Dim WSD As Worksheet
Set WSD = Worksheets(2) 'Data source
Dim CSD As Worksheet
Set CSD = Worksheets(3) 'ChartOutput
'Dim chrt As ChartObject
'Dim cw As Long
'Dim rh As Long
' get the current charts so proper overwriting can happen Dim chtObjs As ChartObjects
Set chtObjs = CSD.ChartObjects
WSD.AutoFilterMode = False ' Turn off autofilter mode
'Dim finalRow As Long ' Find the last row with data
'finalRow = WSD.Cells(Application.Rows.Count, 1).End(xlUp).Row
FirstRow = RowResistiveC
FirstColumn = 5
XelementsC = countXelementsC(FirstRow - 1, FirstColumn) 'Count the x Elements (amperes)
Yelements = countYelements(FirstRow) 'Count the y Elements (Combinations)
LastRow = FirstRow + Yelements - 1 'The last row and column I will read
LastColumn = FirstColumn + XelementsC - 1
'---------------------DRAW THE GRAPHIC----------------------------------------------'
' Delete any previous existing chart
'Dim chtObj As ChartObject
' define the x axis values
WSD.Activate
Set rngChtXVal = WSD.Range(Cells(FirstRow - 1, FirstColumn), Cells(FirstRow - 1, LastColumn))
' add the chart
Charts.Add
With ActiveChart
' make a XY chart
.ChartType = xlXYScatterLines
' remove extra series
Do Until .SeriesCollection.Count = 0
.SeriesCollection(1).Delete
Loop
.Location Where:=xlLocationAsObject, Name:="Estimation Sheets"
End With
'-----------------------------------------------------------------------------
With ActiveChart
.HasTitle = True
.ChartTitle.Characters.Text = "Factor C"
'To Interpolate between the ungiven values
.DisplayBlanksAs = xlInterpolated
'TITLE STYLE
.ChartTitle.AutoScaleFont = False
With .ChartTitle.Font
.Name = "Calibri"
.FontStyle = "Bold"
.Size = 14
.Strikethrough = False
.Superscript = False
.Subscript = False
.OutlineFont = False
.Shadow = False
.Underline = xlUnderlineStyleNone
.ColorIndex = xlAutomatic
.Background = xlAutomatic
End With
'AXIS STYLE-----------------------------------------------------------------------
.Axes(xlCategory).TickLabels.AutoScaleFont = False
With .Axes(xlCategory).TickLabels.Font
.Name = "Arial"
.FontStyle = "Regular"
.Size = 10
.Strikethrough = False
.Superscript = False
.Subscript = False
.OutlineFont = False
.Shadow = False
.Underline = xlUnderlineStyleNone
.ColorIndex = xlAutomatic
.Background = xlAutomatic
With Selection.Border
.ColorIndex = 15
.LineStyle = xlContinuous
End With
End With
.Axes(xlValue).TickLabels.AutoScaleFont = False
With .Axes(xlValue).TickLabels.Font
.Name = "Calibri"
.FontStyle = "Regular"
.Size = 8
.Strikethrough = False
.Superscript = False
.Subscript = False
.OutlineFont = False
.Shadow = False
.Underline = xlUnderlineStyleNone
.ColorIndex = xlAutomatic
.Background = xlAutomatic
End With
End With
'-----------------------------------------------------------------------------
' HEIGHT; WIDTH AND POSITION
GraphLocation = CSD.Cells(Rows.Count, 2).End(xlUp).Row + 3
Dim RngToCover As Range
Set RngToCover = ActiveSheet.Range(Cells(GraphLocation, 2), Cells(GraphLocation + 20, 11))
With ActiveChart.Parent
.Height = RngToCover.Height ' resize
.Width = RngToCover.Width ' resize
.Top = RngToCover.Top ' reposition
.Left = RngToCover.Left ' reposition
End With
' for each row in the sheet
For i = FirstRow To LastRow
Dim chartName As String
' define chart data range for the row (record)
Set rngChtData = WSD.Range(WSD.Cells(i, FirstColumn), WSD.Cells(i, LastColumn))
'To get the serie name that I´m going to add to the graph
Dim serieName As String
Dim varItemName As Variant
WSD.Activate
varItemName = WSD.Range(Cells(i, 1), Cells(i, 4))
serieName = CStr(varItemName(1, 1) + " " + varItemName(1, 2) + " " + varItemName(1, 3) + " " + varItemName(1, 4))
' add series from selected range, column by column
CSD.ChartObjects.Select
With ActiveChart
With .SeriesCollection.NewSeries
.Values = rngChtData
.XValues = rngChtXVal
.Name = serieName
End With
End With
Next i
'We let as last view the page with all the info
CSD.Select
End Sub
I am calling this Sub from other one. The next step will be calling a similar method (exactly the same but other starting point to get the data and some different format properties)for other kind of table and graphic:
Public Sub printGraphics()
Modul4.ClearGraphs
Modul4.generateGraphicsC (RowResistiveC)
Modul4.generateGraphicsT (RowResistiveT)
End Sub
And so on. CountXelements and Yelements counts the number of elements from the Tables Sheet and RowResistiveC, for example, keeps the position of the table.
GenerateGraphicsC works but generateGraphicsT (exactly the same) crush in the line:
With .SeriesCollection.NewSeries
Whit error 91 ( I have a german version of excel at work but it's something like variable object or bloque object not given).
As I suspected the error came from :
CSD.ChartObjects.Select
That works in my solution for the first graph since I'm selecting the single graphic on the sheet, but when I add more it doesn´t.
I just changed that line for:
CSD.ChartObjects(1).Activate
and so on. It works perfectly. I also had to make some adjusments to avoid all the graphs being plotted over the previous one, but it works nice.

How do you format text/strings in VBA?

In the code below, I take some input parameters, either text or a cell, and combine them to form one string using the formatting I need. I need to make Task_Name bold, as well as text like "Lead :". I know you cannot make text in a variable bold, but how do I go about this? This cell I'm storing the value in is eventually used in a Word mail merge.
I need to format part of a string. In the code below, I need to make Task_Name, "Lead : ", etc. all bold.
Function GENERATE_STAFFING_SECTION(Task_Name, Lead_By, Members, Instructions)
Dim tmpSection As String
If Len(Task_Name > 0) And Len(Lead_By) > 0 And Len(Members) > 0 And Len(Instructions) > 0 Then
tmpSection = vbLf _
& Task_Name _
& vbLf & "Lead : " & Lead_By _
& vbLf & "Ambassadors : " & Members _
& vbLf & "Instructions : " & Instructions _
& vbLf
Else
tmpSection = ""
End If
GENERATE_STAFFING_SECTION = tmpSection
End Function
Also, I know it's not the cleanest code, so if there are any other suggestions for improving it, they are most welcome.
Thanks!
You can't add anything to the string directly to make the cell have bold characters.
Once you've written the string out to the cell, you'll need to go back and reprocess the cell.
For example:
With ActiveCell.Characters(Start:=11, Length:=6).Font
.Name = "Arial"
.FontStyle = "Bold"
.Size = 10
.Strikethrough = False
.Superscript = False
.Subscript = False
.OutlineFont = False
.Shadow = False
.Underline = xlUnderlineStyleNone
.ColorIndex = xlAutomatic
End With
This snippet will set only a portion of the cell to bold.
EDIT:
This code could be used to implement the above and give you what you want.
It could be written better, but should give you an idea of what you've got to write:
Public Sub FormatOuput()
Dim i As Integer
'Format Task_name
i = InStr(1, ActiveCell.Text, vbLf)
MakeBold 1, i
'Format 'Lead'
MakeBold i + 1, 4
'Format 'Ambassadors'
i = InStr(i + 1, ActiveCell.Text, vbLf)
MakeBold i+1, 11
'Format 'Instructions'
i = InStr(i + 1, ActiveCell.Text, vbLf)
MakeBold i+1, 10
End Sub
Public Sub MakeBold(startPos As Integer, charCount As Integer)
With ActiveCell.Characters(start:=startPos, length:=charCount).Font
.Name = "Arial"
.FontStyle = "Bold"
.Size = 10
.Strikethrough = False
.Superscript = False
.Subscript = False
.OutlineFont = False
.Shadow = False
.Underline = xlUnderlineStyleNone
.ColorIndex = xlAutomatic
End With
End Sub