I have an excel sheet with some values in the cells (range as u8:u1260). Cell values range from -100 to 100. I want to add conditional formatting where values >=20 and <=-20 should be highlighted in red with bold font. I tried the below code but it's not working.
Microsoft.Office.Interop.Excel.Range range = ws.get_Range("u8", "ab1260");
Microsoft.Office.Interop.Excel.FormatConditions fcs = range.FormatConditions;
Microsoft.Office.Interop.Excel.FormatCondition fc = (Microsoft.Office.Interop.Excel.FormatCondition)fcs.Add
(Microsoft.Office.Interop.Excel.XlFormatConditionType.xlExpression, Type.Missing, "=$u$8:$ab$1260 >= 20");
Microsoft.Office.Interop.Excel.Interior interior = fc.Interior;
interior.Color = ColorTranslator.ToOle(Color.Red);
Related
Sorry for maybe unintelligible title but i cant find out how to write this better.
I've got Excel VBA code that transforms the sheet from Excel for a version to print in a Word. The problem is that when a specific cell in a row in Excel is red colour or is equal to "ENG_AT" text I need to color content of cell which will be printed.
Here you got the original working code sample.
ElseIf Not IsEmpty(calArray(i, 3)) And IsEmpty(calArray(i, 2)) Then
'item
styleName = "N1"
headerText=calArray(i, 12)
.Rows(t).Borders(-3).LineStyle = 7
calArray(i,12) is cell that is going to print.
And this is part where I tried to add my statement
ElseIf Not IsEmpty(calArray(i, 3)) And IsEmpty(calArray(i, 2)) And calArray(i, 16) = "ENG_AT" Then
'item
styleName = "N1"
Dim Text2 As String
Text2 = UCase(calArray(i, 12)
Text2.Interior.Color = RGB(0, 0, 250)
headerText = Text2
'.Font.Underline = True
.Rows(t).Borders(-3).LineStyle = 7
All I've done is only to uppercase a letters, rest is not working.
I would be really happy if someone could explain to me how can I change color of destination cell in Word table or just underline this text.
Thank you in advance for help.
Not knowing the specific variables you are using in your solution, the following is just a generic way to assign a color to the text in a Word table cell.
ActiveDocument.Tables(1).rows(1).Cells(3).Range.Font.ColorIndex = wdRed
Excel 2010.
Issue : I need to plot a *single* *discontinuous* series in a XY-scatter chart *via VBA* without referencing a range in the sheet.
It is easy to achieve that when the Yvalues are laid-out in a sheet range, by inserting blank values at the discontinuities ; as long as one selects 'Show empty cells as: Gaps' in Select Data > Hidden and Empty Cells. Here is an example (the Series2 in red is the one that matters) :
So I was trying to reproduce the same via VBA :
Sub addDiscountinuousSingleSeries()
Dim vx As Variant, vy As Variant
Dim chrtObj As ChartObject, chrt As Chart, ser As Series
Set chrtObj = ActiveSheet.ChartObjects("MyChart"): Set chrt = chrtObj.Chart
Set ser = chrt.SeriesCollection.NewSeries
vx = Array(0.3, 0.3, 0.3, 0.7, 0.7, 0.7)
vy = Array(-1, 1, vbNullString, -1, 1, vbNullString)
'vy = Array(-1, 1, CVErr(xlErrNA), -1, 1, CVErr(xlErrNA)) 'doesn't work either
'vy = Range(RANGE_YVALUES_WITH_BLANK) 'this would work, but I do not want to reference a range
chrt.DisplayBlanksAs = xlNotPlotted 'VBA equivalent to 'Show empty cells as: Gaps'
With ser
ser.Name = "VBA Series"
.XValues = vx
.Values = vy
End With
End Sub
But the blank values in the vy array seems to be ignored and the two vertical bars are now connected, which I am trying to avoid (green series).
I know that I could delete the middle line programmatically, but in the real-life problem I am trying to solve it would not be the right solution (too complex, too slow).
My question : is there a way to specify the series' .Values array to get the expected behavior and get a gap between the two vertical green segments in vba (with only one series and no reference to a sheet range)?
You could just format the lines you don't want. Maybe not the prettiest way, but it'd achieve what your after.
ser.Points(3).Format.Line.Visible = msoFalse
ser.Points(4).Format.Line.Visible = msoFalse
ser.Points(6).Format.Line.Visible = msoFalse
Or:
For i = 1 To ser.Points.Count
If i <> 1 Then k = i - 1 Else k = i
If ser.Values(i) = 0 Or ser.Values(k) = 0 Then
ser.Points(i).Format.Line.Visible = msoFalse
End If
Next
For an Excel spreadsheet order form, I need a way to apply conditional formatting to all rows with one macro, from row 78 down until there is no more data.
Each column has its own conditional formatting formulas. Some have multiple formulas. I tried using the Record Macro function, but since there is so much going on, the resulting VBA code is messy, and I'm not sure how to combine it all.
I don't need someone to write all the code for me, but I'm hoping I can get a little guidance to figure out how to do all of it.
There are about 15 columns that need conditional formatting applied to them. Here are a few columns to show what I'm working with:
A78:
Formula: =AND($A$78="",COUNTA(78:78)>=1) | white text, red fill | Stop
If True
C78:
Format only cells that contain > Specific Text > beginning with > M |
no format | Stop If True
Format only cells that contain > Specific Text > beginning with > F |
no format | Stop If True
Format only cells that contain > No Errors | red background, white
text
D78:
Cell value is greater than 300
You can do this fairly easily with a DO-WHILE Loop. I'll give a start for "D78" and you should be able to finish the rest.
sub formatCells()
Dim count as Integer
Range("D78").Activate
count = 0
Do While ActiveCell.Offset(count, 0).Value <> ""
If ActiveCell.Offset(count, 0).Value > 300 Then
'Do Stuff
End If
count = count + 1
Loop
End Sub
You need to create a FormatCondition object for each rule you want to set. Here are the basics for setting up a formula-based conditional format.
'Set a variable for the formatcondition to make it easier to work with.
Dim fc As FormatCondition
'Create the formatcondition.
strFormula = "=$A1=$B1"
Set fc = Range("A:A").FormatConditions.Add(Type:=xlExpression, Formula1:=strFormula) '(There is a "Formula2" property that only applies if you are using one of the built-in conditional formatting rule types. It does not apply if you are using an xlExpression rule type).
'Move it to the top of the list (optional).
fc.SetFirstPriority
'Set "Stop if True" (optional).
fc.StopIfTrue = True
'Set interior Color (optional).
fc.Interior.Color = RGB(255,0,0) 'red
'Set borders (optional).
arBorders = Array(xlLeft, xlRight, xlTop, xlBottom)
For Each borderConst In arBorders
fc.Borders(borderConst).LineStyle = xlContinuous
Next
'Set font (optional).
fc.Font.Italic = True
fc.Font.Bold = True
fc.Font.Underline = True
I would recommend setting up a procedure as below to simplify this process. I created this one for my own use. It can only set borders and fill color, but could be modified to set font attributes, etc.
Sub AddFormatCondition(rgAppliesTo, strFormula, Optional bSetFirstPriority, Optional FillColor, Optional bBorders, Optional bStopIfTrue)
Dim fc As FormatCondition
Set fc = rgAppliesTo.FormatConditions.Add(Type:=xlExpression, Formula1:=strFormula)
If Not IsMissing(bSetFirstPriority) Then
If bSetFirstPriority Then fc.SetFirstPriority
End If
If Not IsMissing(FillColor) Then
With fc.Interior
.Color = FillColor
End With
End If
If Not IsMissing(bBorders) Then
If bBorders <> 0 Then
arBorders = Array(xlLeft, xlRight, xlTop, xlBottom)
For Each borderConst In arBorders
fc.Borders(borderConst).LineStyle = xlContinuous
Next
End If
End If
fc.StopIfTrue = bStopIfTrue
End Sub
What I want to do is create a macro to look at a column (AF) and based on that value, compare column (BI), (BJ), and/or (BK) together and if its false, highlight the compared cells in yellow. I know that's a little hard to follow but this example should help clarify:
My Sheet has the following columns:
Column AF Column BI Column BJ Column BK
PRODUCT Height Length Width
I need a macro to look at the product type and compare the dimensions for that product as follows:
- If product = A, then Length = Width, if not then highlight Length and Width Cells
- If product = B then Length > Width, if not then highlight Length and Width Cells
- If product = C then Width > Height < Length, if not highlight Length, Width, and Height cells
- If product - D then Width = Length < Height, if not highlight Width, Length, and/or Height
My Data starts on row 3 and ends at row 5002.
I have tried researching this and was only able to find solutions that compare two cells then write a third column. I could combine an IF formula and conditional formatting to achieve this but I don't want to have this run all the time as the sheet will be sorted and color coded. I plan to place this macro into a command button.
Suggest to combine Statements such as Select Case, If...Then...Else, together with Operators And, Or. See the following pages:
https://msdn.microsoft.com/en-us/library/office/gg251599.aspx
https://msdn.microsoft.com/en-us/library/office/gg278665.aspx
https://msdn.microsoft.com/EN-US/library/office/gg251356.aspx
After which you should be able to write something that resembles this:
(Code below is just a sample, it will not work)
Select Case Product
Case A
If Length <> Width Then
Rem Highlight Length And Width Cells
End If
Case B
If Length <= Width Then
Rem Insert here the code to highlight Length And Width Cells
End If
Case C
If Width <= Height And Height >= Length Then
Rem Insert here the code to highlight Length, Width, and Height cells
End If
Case D
If Width <> Length And Length >= Height Then
Rem Insert here the code to highlight Width, Length, and/or Height
End If
End Sub
In case you don’t know to highlight the Width, Length and Height Cells; I suggest to do it manually while recording a macro, this shall give a good starting point.
I suggest to work with objects, defining variables for the Data range, each row being validated, the position of the fields to validate, etc. see below code with comments
Sub Highlight_Cells_based_Comparison()
Dim rData As Range
Dim rRow As Range
Dim rCllsUnion As Range
Rem Set variables to hold Fields position within the DATA range
Dim bPosProd As Byte, bPosHght As Byte, bPosLeng As Byte, bPosWdth As Byte
Rem Set variables to hold Fields values
Rem (data type Variant as don't know type of values these fields are holding, change as appropriated)
Rem see https://msdn.microsoft.com/en-us/library/office/gg251528.aspx)
Dim sProd As String, vHght As Variant, vLeng As Variant, vWdth As Variant
Dim lRow As Long
Rem Set Range (assuming it goes from column C to BK - change as needed)
Rem Not starting from column A on porpuse
Set rData = ActiveSheet.Range("C3:BK5002")
Rem Get Fields position from Header row
Rem Suggest to use this method instead of hard coding columns
On Error Resume Next
With rData
bPosProd = WorksheetFunction.Match("PRODUCT", .Rows(1), 0)
bPosHght = WorksheetFunction.Match("Height", .Rows(1), 0)
bPosLeng = WorksheetFunction.Match("Length", .Rows(1), 0)
bPosWdth = WorksheetFunction.Match("Width", .Rows(1), 0)
End With
If Err.Number <> 0 Then Exit Sub
On Error GoTo 0
Rem Loop thru each row excluding header
For lRow = 2 To rData.Rows.Count
Set rRow = rData.Rows(lRow)
With rRow
Rem Get Row Field values
sProd = .Cells(bPosProd).Value2
vHght = .Cells(bPosHght).Value2
vLeng = .Cells(bPosLeng).Value2
vWdth = .Cells(bPosWdth).Value2
Select Case sProd
Case A 'Change value of A as required
Rem If product = A, then Length = Width, if not then highlight Length and Width Cells
Rem If Length <> Width Then Highlight Length And Width 'Cells
If vLeng <> vWdth Then
Set rCllsUnion = Union(.Cells(bPosLeng), .Cells(bPosWdth))
Rem Suggest to use a subroutine for this piece as it's a repetitive task
Rem see https://msdn.microsoft.com/en-us/library/office/gg251648.aspx
GoSub CllsUnion_Highlight
End If
Case B
Rem repeat as in Case A with required changes
Case C
'...
Case D
'...
End Select: End With: Next
Exit Sub
Rem Subroutine to highlight cells
CllsUnion_Highlight:
With rCllsUnion.Interior
.Color = 65535
.TintAndShade = 0
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.PatternTintAndShade = 0
End With
Return
End Sub
I am new to VBA and wanted to ask if you could help me.
I have this VB6 code:
For i = 2 To rowCount - 2
' Fill Ji with a formula(=MID(Fi,11,9)) and apply format.
Set oRng = oSheet.Range(Cells(i, 10), Cells(rowCount - 2, 10))
**oRng.formula = "=MID(Cells(i,6),11,9)"**
oRng.NumberFormat = "[$-F400]hh:mm:ss"
Next i
I want to assign a formula to the range
Tried this code but, has a problem when I assign the formula. It doesn't recognizes the Cell(i,6) as Cell, but As string "Cell(i,6)".
Can anyone help me?
You don't want the loop as you're putting the formula into all cells at once:
' Fill Ji with a formula(=MID(Fi,11,9)) and apply format.
Set oRng = oSheet.Range(oSheet.Cells(2, 10), oSheet.Cells(rowCount - 2, 10))
oRng.formulaR1C1 = "=MID(RC6,11,9)+0"
oRng.NumberFormat = "[$-F400]hh:mm:ss"
Note: I added a +0 to your formula to convert text to true time values.
Try "=MID(" & Cells(i,6).Address(False,False) &",11,9)"
Include the Address part only if you want a relative reference