How can I use VBA to dynamically border my columns? - vba

I'm currently working with Excel and here's what I'd like to do. When pasting a table in Excel, I would like for that table to appear with borders to the left of all columns. I was wondering what would be the code to do this. Here is what I have so far:
'affichage des cadres autour des cases et colonnes
Dim lastColumnNumber As Long
lastColumnNumber = Cells(1, Columns.Count).End(xlToLeft).Column
Dim i As Integer
i = 0
Dim col As String
col = "A"
Do While i <= lastColumnNumber
With Columns("col:col").Borders(xlEdgeRight)
.LineStyle = xlContinuous
.Weight = xlMedium
.ColorIndex = 1
End With
col = Mid(Range(col & 1).Offset(, 1).Address, 2, 1)
i = i + 1
Loop
Which doesn't fire up any errors but doesn't work either. If I try this instead:
'affichage des cadres autour des cases et colonnes
With Columns("A:D").Borders(xlEdgeRight)
.LineStyle = xlContinuous
.Weight = xlMedium
.ColorIndex = 1
End With
I get that only column D has a left border (not even A through D). That's why I tried the loop.

Your code doesn't do anything that you see because your data is not in column COL. You used the text string "COL" instead of the value of the variable col. The following:
With Columns("col:col").Borders(xlEdgeRight)
Should be:
With Columns(col & ":" & col).borders(xlEdgeRight)
Though I'm not completely sure why you're bothering to get the column letter instead of say:
With Columns(i + 1).borders(xlEdgeRight)

Related

Highlight Row-Column of selected cell

Be gentle guys, I'm not a programmer.
I got this snippit of code off the internet many many moons ago. I would give credit, but I don't remember where it came from.
Sub Worksheet_SelectionChange(ByVal Target As Excel.Range)
Static xRow
Static xColumn
If xColumn <> "" Then
With Columns(xColumn)
.Interior.ColorIndex = xlNone
End With
With Rows(xRow)
.Interior.ColorIndex = xlNone
End With
End If
pRow = Selection.Row
pColumn = Selection.Column
xRow = pRow
xColumn = pColumn
With Columns(pColumn)
.Interior.ColorIndex = 19
.Interior.Pattern = xlSolid
End With
With Rows(pRow)
.Interior.ColorIndex = 19
.Interior.Pattern = xlSolid
End With
End Sub
The above code highlights rows and columns of a selected sell. The problem is that it highlights columns from 1 to 1048576, which causes the vertical scroll bar to get tiny. Plus if there is any color coding in the spreadsheet it screws that up. I decided to write my own highlighter. I put a border around my selected row,column and only do it for 500 rows. It works, almost. The problem is that something in my code cancels the copy command, and will not allow me to paste, which did not happen in the code above. Copy/Paste is a must. Any help would be greatly appreciated.
Sub Worksheet_SelectionChange(ByVal Target As Excel.Range)
Range("A1:N500").Borders(xlEdgeLeft).Weight = xlThin
Range("A1:N500").Borders(xlEdgeTop).Weight = xlThin
Range("A1:N500").Borders(xlEdgeBottom).Weight = xlThin
Range("A1:N500").Borders(xlEdgeRight).Weight = xlThin
Range("A1:N500").Borders(xlInsideVertical).Weight = xlThin
Range("A1:N500").Borders(xlInsideHorizontal).Weight = xlThin
Range("A1:N500").Borders(xlEdgeLeft).Color = vbBlack
Range("A1:N500").Borders(xlEdgeTop).Color = vbBlack
Range("A1:N500").Borders(xlEdgeBottom).Color = vbBlack
Range("A1:N500").Borders(xlEdgeRight).Color = vbBlack
Range("A1:N500").Borders(xlInsideVertical).Color = vbBlack
Range("A1:N500").Borders(xlInsideHorizontal).Color = vbBlack
Dim SplitAddress() As String
SplitAddress = Split(ActiveCell.Address, "$")
Dim RowSelection As String
RowSelection = "A" & SplitAddress(2) & ":" & "N" & SplitAddress(2)
Dim ColSelection As String
ColSelection = SplitAddress(1) & "1" & ":" & SplitAddress(1) & "500"
With Range(RowSelection)
.BorderAround Weight:=xlThick, Color:=RGB(255, 0, 0)
End With
With Range(ColSelection)
.BorderAround Weight:=xlThick, Color:=RGB(255, 0, 0)
End With
End Sub
try this.
it is work in progress
it copies the format, as the default format, from the very last cell in worksheet
the code uses no copy/paste to do the borders
i am still working on copy/paste between cells that you are having trouble with
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Application.ScreenUpdating = False
Dim aaa As DisplayFormat
Set aaa = Range("XFD1048576").DisplayFormat ' copy format from very last cell (it is a cheat)
Range("A1:N500").Borders.Color = aaa.Borders.Color ' revert border color to its default
Range("A1:N500").Borders.LineStyle = aaa.Borders.LineStyle
Dim i As Integer
For i = xlEdgeLeft To xlEdgeRight ' loop the four outside borders (7 to 10)
Target.EntireRow.Resize(1, 8).Borders.Item(i).Color = vbRed
Target.EntireRow.Resize(1, 8).Borders.Item(i).Weight = xlThick
Target.EntireColumn.Resize(500, 1).Borders.Item(i).Color = vbRed
Target.EntireColumn.Resize(500, 1).Borders.Item(i).Weight = xlThick
Next i
Application.ScreenUpdating = True
End Sub

Trying to add all borders to range with variable row count in excel vba

I am trying to add all borders to the contents below the headers that I have. The range would be A7 to Ox where x is the last row of content. The first part of the code listed looks for CFS-GHOST-DJKT and deletes the row which works perfectly. I am unsure about how to select the lower ending row correctly.
Dim x As Long
For x = Cells(Rows.Count, "A").End(xlUp).Row To 7 Step -1
If Cells(x, "A") = "CFS-GHOST-DJKT" Then Rows(x).Delete
'Add Gridlines=========================================================
Range(A7, Ox).Select
With Selection.Borders
.LineStyle = xlContinuous
.ColorIndex = 0
.TintAndShade = 0
.Weight = xlThin
End With
Using a term of Range(A7, Ox) is telling VBA to select the rectangular area defined by the Address of the variable (of type Range) A7 as one corner and the Address of the variable (also of type Range) Ox as the other corner.
As you have defined neither of those variables, your code fails.
Try this instead:
Dim x As Long
For x = Cells(Rows.Count, "A").End(xlUp).Row To 7 Step -1
If Cells(x, "A") = "CFS-GHOST-DJKT" Then Rows(x).Delete
Next
With Range("A7:O" & Cells(Rows.Count, "A").End(xlUp).Row).Borders
.LineStyle = xlContinuous
.ColorIndex = 0
.TintAndShade = 0
.Weight = xlThin
End With

VBA - the same formatting for multiple dynamic ranges

I want to format data in 2 columns in the same pattern. Each data column has its length based on upper boundary of result array. I initially formatted them both separately and it was working as intended, but I want to keep the code as lean as possible.
I tried the code below, but it created a range from 1st range to the 2nd instead of matching a sum of these ranges:
With statsWS
With Range(.Range("b2:c" & UBound(vGoals) + 1), _
.Range("e2:f" & UBound(vAssists) + 1))
With .Borders
.LineStyle = xlContinuous
.Color = rgbGrey
End With
End With
End With
something like this:
With statsWS.Range("b2:c" & (UBound(vGoals) + 1) & ",e2:f" & (UBound(vAssists) + 1)).Borders
.LineStyle = xlContinuous
.Color = rgbGrey
End With
You could use Chris Neilsen's suggestion:
With statsWS
With Union(.Range("B2:C" & UBound(vGoals) + 1), .Range("E2:F" & UBound(vAssists) + 1))
With .Borders
.LineStyle = xlContinuous
.Color = rgbGrey
End With
End With
End With
But if you want to keep your code lean then you could pass the ranges to another Subroutine to handle the formatting. Separating the business logic from the display:
Usage:
ApplyBorders .Range("B2:C" & UBound(vGoals) + 1), .Range("E2:F" & Bound(vAssists) + 1)
Code:
Sub ApplyBorders(ParamArray Ranges())
Dim x As Long
Dim r As Range
Set r = Ranges(0)
For x = 1 To UBound(Ranges())
Set r = Union(r, Ranges(x))
Next
With r.Borders
.LineStyle = xlContinuous
.Color = rgbGrey
End With
End Sub
Note: Because ApplyStandardBorders uses a ParamArray you can pass anywhere from 0 to 60 parameters to it (Only 29 in Excel 2003).
you can also use the Range("Address1,Address2") method to get the union of different ranges
With statsWS
With .Range(.Range("b2:c" & UBound(vGoals) + 1).Address & "," & .Range("e2:f" & UBound(vAssists) + 1).Address).Borders
.LineStyle = xlContinuous
.Color = rgbGrey
End With
End With

Color code the columns

In an excel file, I need to color code a column cell depending upon the number of "Yes" in that Column. If there are no "Yes" : Red color; one "Yes": Yellow color: 2 or more than 2 "Yes": Green color.
Can this be done by some macro ?
Update:
Have made this macro but i am not able to run or debug it as it gives an error of Overflow;
The variable N is taking a value of 32676 even after I have assigned it zero value .
Sub testcolor()
Dim i As Integer
Dim j As Integer
Dim N As Integer
Dim z As Integer
Dim val As String
i = 7
j = 5
N = 0
MsgBox (N)
For j = 5 To 15
Do While i < 13
val = ActiveSheet.Cells(i, j).Value
If val = "Yes" Then N = N + 1
Loop
If N = 0 Then
Range(i + 2, j).Select
With Selection.Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.Color = 255
.TintAndShade = 0
.PatternTintAndShade = 0
End With
End If
If N = 1 Then
Range(i + 2, j).Select
With Selection.Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.Color = 65535
.TintAndShade = 0
.PatternTintAndShade = 0
End With
End If
If N > 1 Then
Range(i + 2, j).Select
With Selection.Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.Color = 5296274
.TintAndShade = 0
.PatternTintAndShade = 0
End With
End If
Next j
End Sub
Another way to solve this is by using Conditional Formatting.
Select the area you wish to format. Looks like it's range E14:K14 in your book.
Click Home > Conditional Formatting > New Rule.
In the New Formatting Rule dialog box, click "Use a formula to determine which cells to format".
Under "Format values where this formula is true", type the following formula:
=AND(E14="Yes",COUNTIF(E:E,"Yes")>=2,ROW()>=7,ROW()<=13)
Next, click the "Format" button.
Now, simply choose the design you wish. Perhaps a colored background is enough.
The GREEN formula is done, but you have to repeat these steps for the yellow and red formulas.
The yellow formula:
=AND(E14="Yes",COUNTIF(E:E,"Yes")<2;COUNTIF(E:E,"Yes")>0,ROW()>=7,ROW()<=13)
And the red formula:
=AND(E14="Yes",COUNTIF(E:E,"Yes")=0,ROW()>=7,ROW()<=13)
Don't forget to apply your format conditions (green/yellow/red background).
Let me break the GREEN formula down for you:
AND() - All of the conditions in between these () brackets need to be met.
E14="Yes" - The cell has to contain the word "Yes".
COUNTIF(E:E,"Yes")>=2 - The column must have 2 or more "Yes".
ROW()>=7,ROW()<=13) - The cell has to be somewhere in between rows 7 to 13.
It's quite easy to change these parameters whenever you need to. And perhaps it's easier than jumping into a big chunk of code. It may look quite difficult using Conditional Formatting with multiple conditions, but once you get a hang of it you won't stop using it.
Try this (set RGB and ColorIndex accordingly, did not get if you want cell text color or fill color):
Sub ConditionalColorColumn()
count = Application.WorksheetFunction.CountIf(arg1:=Range("D:D"), arg2:="yes")
'MsgBox count
If count = 1 Then
ActiveSheet.Range("D:D").Font.Color = RGB(255, 255, 0)
ActiveSheet.Range("D:D").Interior.ColorIndex = 6
ElseIf count >= 2 Then
ActiveSheet.Range("D:D").Font.Color = RGB(255, 255, 0)
ActiveSheet.Range("D:D").Interior.ColorIndex = 6
Else
ActiveSheet.Range("D:D").Font.Color = RGB(255, 255, 0)
ActiveSheet.Range("D:D").Interior.ColorIndex = 6
End If
End Sub
APPENDED: you can try this for multiple columns
Sub ConditionalColorMultiColumn()
'Dim arr As Variant
'Dim desCell As Range
arr = Array("E", "F", "G", "H", "I","J","K")
For i = 0 To UBound(arr)
Set rngg = Range(arr(i) & 7 & ":" & arr(i) & 12)
'rngg.Select
Set desCell = Cells(14, arr(i))
Count = Application.WorksheetFunction.CountIf(arg1:=rngg, arg2:="yes")
'MsgBox count
If Count = 1 Then
desCell.Interior.ColorIndex = 6
ElseIf Count >= 2 Then
desCell.Interior.ColorIndex = 4
Else: desCell.Interior.ColorIndex = 3
End If
Set desCell = Nothing
Set rngg = Nothing
Next
End Sub

Count like values then put count in cell

I'm trying to loop through column A- "Domains", and get total pages per domain. For each row, if the domain is the same, count the total. Once you get to a new domain, put that final page count in the top right box of the domain in Column C.
I'm new to VBA- I'm trying something like this. Any guidance would be appreciated.
Sub TestScript()
iMaxRow = 11000
Range("B1").Select
pagesCounter = 0 'loop counter for each page in site
countEntryCell = 1 'where you put the total # pages for that site
For iRow = 1 To iMaxRow
'loop through column B, while domain name is the same... count rows
'then put final count in count column
If ActiveCell = ActiveCell.Offset(-1, 0) Then
pagesCounter = pagesCounter + 1
Else
'Copy pages count to column c within the box
End If
ActiveCell.Offset(1, 0).Select 'select next row
Next iRow
End Sub
UPD:
Try this one:
Sub TestScript()
Dim lastrow As Long
Dim rng As Range, c As Range
'change Sheet1 to suit
With ThisWorkbook.Worksheets("Sheet1")
lastrow = .Cells(.Rows.Count, "A").End(xlUp).Row
Set rng = .Range("A2:A" & lastrow)
For Each c In rng
If c.Value <> c.Offset(-1).Value Then
'c.offset(,2) gives you column C
c.Offset(, 2).Value = WorksheetFunction.CountIf(rng, c.Value)
'aplly border
With c.Offset(-1).Resize(, 3).Borders(xlEdgeBottom)
.LineStyle = xlContinuous
.ColorIndex = 0
.TintAndShade = 0
.Weight = xlMedium
End With
End If
Next c
End With
End Sub
Result: