I'm going to be generating some large excel cell values by appending MS Project tasks info to each other, and then I'll be calculating if a certain task has changed since the last report. I need to color just the changed tasks in the cell, but it will be in a long string with lots of other tasks. It would be really nice if I could change the color of tasks as I append them.
I'm thinking I've got to use some sort of 'With' statement, but I don't where to start.
With cell
.FutureFormat red
.Value = .Value & "abc"
End With
Or something like
Stringthing = "ABC"
Stringthing.Format = red
Cell.value = cell.value & Stringthing
Here is an example code:
Option Explicit
Public Sub AppendStringAndColorize()
Dim str As String
str = "abc"
Dim cell As Range
Set cell = Range("A1")
Dim CellLength As Long
CellLength = Len(cell.Value)
With cell
.Value = .Value & str
.Characters(Start:=CellLength + 1, Length:=Len(str)).Font.Color = vbRed
End With
End Sub
you first need to remember the length of the original value as start point to colorize the characters after that value.
To keep the old colors:
Public Sub AppendStringAndColorizeKeepingOldColors()
Dim str As String
str = "abc"
Dim cell As Range
Set cell = Range("A1")
Dim CharList() As Variant
Dim CurrentColor As Double
CurrentColor = cell.Characters(1, 1).Font.Color
Dim iColor As Long 'color change counter
iColor = 1
ReDim CharList(1 To 2, 1 To 1) As Variant
CharList(1, iColor) = CurrentColor
Dim CellLength As Long
CellLength = cell.Characters.Count
'analyze colors and save into array
Dim i As Long
For i = 1 To CellLength
If cell.Characters(i, 1).Font.Color <> CurrentColor Then
CurrentColor = cell.Characters(i, 1).Font.Color
iColor = iColor + 1
ReDim Preserve CharList(1 To 2, 1 To iColor)
CharList(1, iColor) = CurrentColor
End If
CharList(2, iColor) = CharList(2, iColor) + 1
Next i
'change cell value (append only!)
cell.Value = cell.Value & str
're-write colors
Dim ActChar As Long
ActChar = 1
For i = LBound(CharList) To UBound(CharList, 2)
cell.Characters(Start:=ActChar, Length:=CharList(2, i)).Font.Color = CharList(1, i)
ActChar = ActChar + CharList(2, i)
Next i
'color for new appended string
cell.Characters(Start:=CellLength + 1, Length:=Len(str)).Font.Color = vbYellow 'desired color
End Sub
Here's how you add new text without disturbing the existing formatting.
NOTE: this approach is only good up to about 250 characters total length. Not sure if there's any way after you hit that point.
Public Sub Tester()
Const NUM As Long = 20
Const TXT As String = "The quick brown for jumped over the lazy dogs"
Dim colors, i, l
colors = Array(vbRed, vbBlue)
With ActiveSheet.Range("A1")
For i = 1 To NUM
l = Len(.Value)
'Error here if trying to access characters after ~250
With .Characters(Start:=l + 1, Length:=Len(TXT) + 1)
.Text = TXT & vbLf
.Font.Color = colors(i Mod 2)
End With
Next i
End With
End Sub
Related
I have the following macro that I got from someone, and trying to modify it to suit my purpose.
I'm trying to alter this macro to find and highlight cells that have duplicate values within each cell,
for example, it should highlight B62 and B63 (green),
and color font red the duplicate values (i.e. B_HWY_1010 in B62, and B_HWY_1015 in B63)
Sub Dupes()
Dim d As Object
Dim a As Variant, itm As Variant
Dim i As Long, k As Long
Dim rng As Range
Dim bColoured As Boolean
Set d = CreateObject("Scripting.Dictionary")
Set rng = Range("B1", Range("B" & Rows.Count).End(xlUp))
a = rng.Value
For i = 1 To UBound(a)
For Each itm In Split(a(i, 1), ",")
d(itm) = d(itm) + 1
Next itm
Next i
Application.ScreenUpdating = False
For i = 1 To UBound(a)
k = 1
bColoured = False
For Each itm In Split(a(i, 1), ",")
If d(itm) > 1 Then
If Not bColoured Then
rng.Cells(i).Interior.Color = vbGreen
bColoured = True
End If
rng.Cells(i).Characters(k, Len(itm)).Font.Color = RGB(244, 78, 189)
End If
k = k + Len(itm) + 1
Next itm
Next i
Application.ScreenUpdating = True
End Sub
Any help or advise is appreciated.
The following will do that
Option Explicit
Public Sub Example()
Dim Cell As Range
For Each Cell In Range("A1:A10")
HighlightRepetitions Cell, ", "
Next Cell
End Sub
Private Sub HighlightRepetitions(ByVal Cell As Range, ByVal Delimiter As String)
If Cell.HasFormula Or Cell.HasArray Then Exit Sub ' don't run on formulas
Dim Dict As Object
Set Dict = CreateObject("Scripting.Dictionary")
Dim Data() As String
Data = Split(Cell.Value, Delimiter) ' split data in the cell by Delimiter
Dim StrLen As Long ' length of the string that was already processed
Dim i As Long
For i = LBound(Data) To UBound(Data) ' loop through all data items
Dim DataLen As Long
DataLen = Len(Data(i)) 'get length of current item
If Dict.Exists(Data(i)) Then
' item is a repetition: color it
Cell.Characters(StrLen + 1, DataLen).Font.Color = vbRed
Cell.Interior.Color = vbGreen
Else
' item is no repetition: add it to the dictionary
Dict.Add Data(i), Data(i)
End If
StrLen = StrLen + DataLen + Len(Delimiter) ' calculate the length of the processed string and add length of the delimiter
Next i
End Sub
The following items would be colored:
You can turn ScreenUpdating off before looping in Sub Example() and turn on after the loop to stop it from flickering. Note this will not run on formuas, as parts of formula results cannot be colored. This can be prevented by using If Cell.HasFormula Or Cell.HasArray Then Exit Sub as first line.
Please, try the next code, too:
Sub findComaDelDuplicates()
Dim sh As Worksheet, arr, itm, arrInt, i As Long, rngS As Range, pos As Long
Dim arrDif As Long, j As Long, startPos As Long, arrPos, k As Long, mtch
Set sh = ActiveSheet
With sh.Range("B1", Range("B" & sh.rows.count).End(xlUp))
arr = .value 'put the range value in an array to make the iteration faster
.ClearFormats 'clear previous format
.Font.Color = vbBlack 'make the font color black
End With
For i = 1 To UBound(arr) 'iterate between the array elements:
arrInt = Split(arr(i, 1), ",") 'split the content by comma delimiter
ReDim arrPos(UBound(arrInt)) 'redim the array keeping elements already formatted
For Each itm In arrInt 'iterate between the comma separated elements
arrDif = UBound(arrInt) - 1 - UBound(Filter(arrInt, itm, False)) 'find how many times an element exists
If arrDif > 0 Then 'if more then an occurrence:
If rngS Is Nothing Then 'if range to be colored (at once) does not exist:
Set rngS = sh.Range("B" & i) 'it is crated
Else
Set rngS = Union(rngS, sh.Range("B" & i)) 'a union is made from the previous range and the new one
End If
mtch = Application.match(itm, arrPos, 0) 'check if the itm was already processed:
If IsError(mtch) Then 'if itm was not processed:
For j = 1 To arrDif + 1 'iterate for number of occurrences times
If j = 1 Then startPos = 1 Else: startPos = pos + 1 'first time, inStr starts from 1, then after the first occurrence
pos = InStr(startPos, sh.Range("B" & i).value, itm) 'find first character position for the itm to be colored
sh.Range("B" & i).Characters(pos, Len(itm)).Font.Color = vbRed 'color it
Next j
arrPos(k) = itm 'add the processed itm in the array
End If
End If
Next
Erase arrInt 'clear the array for the next cell value
Next i
If Not rngS Is Nothing Then rngS.Interior.Color = vbGreen 'color the interior cells of the built range
End Sub
Attention: The above code puts the range in an array to iterate much faster. But, if the range does not start form the first row, the cells to be processed must be obtained by adding to i the rows up to the first of the range. The code can be adapted to make this correlation, but I am too lazy to do it now...:)
Background: I have already used the 'conditional' formatting to highlight the 10 lowest values in each row in light red.
Now, I am trying to compose a code that searches each row for the red marked cells and copies their name from the header row to a new sheet.
What I am aiming for is the following: a code that searches each row for the cells in red and that copies the name (in header) to the same row in another sheet (=result sheet). This should result in a result sheet with 11 columns: first column being the dates and the following 10 columns in that row being the names of the lowest values for that date.
This is the code that I have so far but it does not work:
Sub CopyReds()
Dim i As Long, j As Long
Dim sPrice As Worksheet
Dim sResult As Worksheet
Set sPrice = Sheets("Prices")
Set sResult = Sheets("Result")
i = 2
For j = 2 To 217
Do Until i = 1086
If sPrice.Cells(j, i).Offset(j, 0).Interior.Color = 13551615 Then
sPrice.Cells(j, i).Copy Destination:=sResult.Cells(2, 2).Offset(j, 1)
End If
Loop
Next j
End Sub
Update: screenshot worksheet
Update 2: Screenshot result sample
I think your code should look something like this:
Option Explicit
Sub CopyReds()
Dim sPrice As Worksheet: Set sPrice = Sheets("Prices")
Dim sResult As Worksheet: Set sResult = Sheets("Result")
Const colPriceName As Long = 2 ' The column in which cells can be colored red and contains the names to copy
Const clrCopy As Long = 13551615 ' The color which indicates that the cell should be copied (red)
Const colResult As Long = 2 ' The column where the results should be copied
Const rowResultFirst As Long = 2 ' First row on sResult to use for output
Dim rowResult As Long: rowResult = rowResultFirst
Dim rowPrice As Long: For rowPrice = 2 To sPrice.UsedRange.Rows.Count - sPrice.UsedRange.Row + 1 ' Loop until last row
If DisplayedColor(sPrice.Cells(rowPrice, colPriceName)) = clrCopy Then
sResult.Cells(rowResult, colResult).Value = sPrice.Cells(rowPrice, colPriceName).Value
rowResult = rowResult + 1
End If
Next rowPrice
End Sub
Update: handling conditional formatting
If you use conditional formatting then VBA does not read the actual color displayed but the color which would be shown without Conditional Formatting. So you need a vehicle to determine the displayed color. I wrote this code based on this source but refactored it significantly, e.g. now it did not work in international environment and its readability was poor:
Function DisplayedColor(rngCell As Range, Optional bCellInterior As Boolean = True, Optional bReturnColorIndex As Long = False) As Long
Dim ewbTemp As Workbook: Set ewbTemp = Application.Workbooks.Add() ' Creates a new workbook, so that none of the cells of other workbooks is tampered with (not even temporarily) - this may be overkill, you may centralize this object or use existing cells
DisplayedColor = -1 ' Assume Failure and indicate Error
If 1 < rngCell.Count Then
Debug.Print "Error in DisplayedColor: rngCell contains more than 1 cell"
Exit Function
End If
Dim objTarget As Object: Set objTarget = rngCell
Dim i As Long: For i = 1 To rngCell.FormatConditions.Count
With rngCell.FormatConditions(i)
Dim bFormatConditionActive As Boolean: bFormatConditionActive = False
Dim varValue As Variant: varValue = rngCell.Value
Dim strFormula1 As String: strFormula1 = FormulaFromFormulaLocal(.Formula1, ewbTemp.Worksheets(1).Cells(1, 1))
Dim varEval1 As String: varEval1 = rngCell.Worksheet.Evaluate(strFormula1)
If .Type = xlCellValue Then
Select Case .Operator
Case xlEqual
bFormatConditionActive = varValue = varEval1
Case xlNotEqual
bFormatConditionActive = varValue <> varEval1
Case xlGreater
bFormatConditionActive = varValue > varEval1
Case xlGreaterEqual
bFormatConditionActive = varValue >= varEval1
Case xlLess
bFormatConditionActive = varValue < varEval1
Case xlLessEqual
bFormatConditionActive = varValue <= varEval1
Case xlBetween, xlNotBetween
Dim strFormula2 As String: strFormula2 = FormulaFromFormulaLocal(.Formula2, ewbTemp.Worksheets(1).Cells(1, 1))
Dim varEval2 As String: varEval2 = rngCell.Worksheet.Evaluate(strFormula2)
bFormatConditionActive = varEval1 <= varValue And varValue <= varEval2
If .Operator = xlNotBetween Then
bFormatConditionActive = Not bFormatConditionActive
End If
Case Else
Debug.Print "Error in DisplayedColor: unexpected Operator"
Exit Function
End Select
ElseIf .Type = xlExpression Then
bFormatConditionActive = varEval1
Else
Debug.Print "Error in DisplayedColor: unexpected Type"
Exit Function
End If
If bFormatConditionActive Then
Set objTarget = rngCell.FormatConditions(i)
Exit For
End If
End With
Next i
If bCellInterior Then
If bReturnColorIndex Then
DisplayedColor = objTarget.Interior.ColorIndex
Else
DisplayedColor = objTarget.Interior.Color
End If
Else
If bReturnColorIndex Then
DisplayedColor = objTarget.Font.ColorIndex
Else
DisplayedColor = objTarget.Font.Color
End If
End If
ewbTemp.Close False
End Function
Function FormulaFromFormulaLocal(strFormulaLocal As String, rngDummy As Range) As String
Dim strOldFormula As String: strOldFormula = rngDummy.Formula
rngDummy.FormulaLocal = strFormulaLocal
FormulaFromFormulaLocal = rngDummy.Formula
rngDummy.Formula = strOldFormula
End Function
Please also note the change in the If statement of CopyReds (now it calls the above function).
I think that your algorithm should be redesigned: instead of testing the cells displayed color, check if the value is below a limit. This limit can be calculated with WorksheetFunction.Small, which returns the n-th smallest element.
Sub CopyReds()
Dim sPrice As Worksheet: Set sPrice = Sheets("Prices")
Dim sResult As Worksheet: Set sResult = Sheets("Result")
Const colPriceName As Long = 2 ' The column in which cells can be colored red and contains the names to copy
Const clrCopy As Long = 13551615 ' The color which indicates that the cell should be copied (red)
Const colResult As Long = 2 ' The column where the results should be copied
Const rowResultFirst As Long = 2 ' First row on sResult to use for output
Const lngCount As Long = 10 ' Copy lngCount lowest elements (the actual number may be higher due to ties)
Const colSort As Long = 2 ' The column in which cells contain the values from which the lowest lngCount should be selected
Dim varLimit As Variant: varLimit = Application.WorksheetFunction.Small(sPrice.UsedRange.Cells(2, colSort).Resize(sPrice.UsedRange.Rows.Count - 1, 1), 10)
Dim rowResult As Long: rowResult = rowResultFirst
Dim rowPrice As Long: For rowPrice = 2 To sPrice.UsedRange.Rows.Count - sPrice.UsedRange.Row + 1 ' Loop until last row
If sPrice.Cells(rowPrice, colSort).Value <= varLimit Then
sResult.Cells(rowResult, colResult).Value = sPrice.Cells(rowPrice, colPriceName).Value
rowResult = rowResult + 1
End If
Next rowPrice
End Sub
Based on the screenshots, I revised the code:
Sub CopyReds()
Dim sPrice As Worksheet: Set sPrice = Sheets("Prices")
Dim sResult As Worksheet: Set sResult = Sheets("Result")
Const rowResultFirst As Long = 2 ' First row on sResult to use for output
Const rowPriceFirst As Long = 2 ' First row on sPrice to process
Const lngCount As Long = 10 ' Copy lngCount lowest elements (the actual number may be higher due to ties)
Const colDate As Long = 1 ' The column which contains the dates
Const colValueStart As Long = 2 ' The column where values start
Dim rowResult As Long: rowResult = rowResultFirst
Dim rowPrice As Long: For rowPrice = rowPriceFirst To sPrice.UsedRange.Rows.Count - sPrice.UsedRange.Row + 1 ' Loop until last row
Dim colResult As Long: colResult = 1
sResult.Cells(rowResult, colResult).Value = sPrice.Cells(rowPrice, colDate).Value
colResult = colResult + 1
Dim varLimit As Variant: varLimit = Application.WorksheetFunction.Small(sPrice.Cells(rowPrice, colValueStart).Resize(1, sPrice.UsedRange.Columns.Count - colValueStart + 1), lngCount)
Dim colPrice As Long: For colPrice = colValueStart To sPrice.UsedRange.Columns.Count - colValueStart + 1
If sPrice.Cells(rowPrice, colPrice).Value <= varLimit Then
sResult.Cells(rowResult, colResult).Value = sPrice.Cells(rowResultFirst - 1, colPrice).Value
colResult = colResult + 1
End If
Next colPrice
rowResult = rowResult + 1
Next rowPrice
End Sub
Just to clarify my comment, you need to "advance" either the Cells(j, i) or the Offset(j, 0).
If you decided to use For loops, try to stick with it for both cases:, see code below:
For j = 2 To 217
For i = 2 To 1086
Debug.Print sPrice.Cells(j, i).Interior.Color ' <-- for Debug only
If sPrice.Cells(j, i).Interior.Color = 13551615 Then
sPrice.Cells(j, i).Copy Destination:=sResult.Cells(2, 2).Offset(j, 1)
End If
Next i
Next j
I have the following Excel cells:
D001
D002
D003
345
(In the same cell)
I need to add a string of text after every line on the same cell, like this:
D001 First Text
D0002 Second Text
D003 Third Text
345 Fouth Text
I found a code which allows me to count how many lines there are on the same cell, but I dont find any way of using it to write after the text on each of those lines:
Public Sub CountLines()
Dim H1 As Double
Dim H2 As Double
Dim row As Long
row = 1
While Cells(row, 1).Value <> ""
With Cells(row, 1)
.WrapText = False
H1 = .height
.WrapText = True
H2 = .height
.Offset(0, 1).Value = H2 / H1
End With
row = row + 1
Wend
End Sub
I guess the right way of doing it is by using a For to write text before any change of line he finds (Ch(10)) on VBA, but i havent been able to make it work
Thanks for the help.
Adding Text To Count Line Breaks
This code will loop through all cells with any value in Column A.
I have recreated your data set in my Excel:
The code will break up each line, add which line it is, and move on to the next:
Below is the code:
Sub AddText()
Dim ws As Worksheet: Set ws = ThisWorkbook.Sheets(1)
Dim myCell As Variant, myRange As Range, tempArr() As String
Dim i As Integer
Set myRange = ws.Range("A1", ws.Cells(ws.Rows.Count, "A").End(xlUp))
For Each myCell In myRange
tempArr = Split(myCell, Chr(10))
myCell.Value = ""
For i = 0 To UBound(tempArr)
tempArr(i) = tempArr(i) & " text " & i
If i = UBound(tempArr) Then
myCell.Value = myCell.Value & tempArr(i)
Else: myCell.Value = myCell.Value & tempArr(i) & Chr(10)
End If
Next i
Next myCell
End Sub
If you want it to count from base 1 instead of base 0, change the lines myCell.Value = myCell.Value & tempArr(i) (and the following one in the If statement) to myCell.Value = myCell.Value & tempArr(i) + 1
I should mention again that this is already set up for a dynamic range in Column A. Meaning if you add more data formatted the same way in A2, the code will apply itself to that as well, all the way to the last set of data in column A.
Dim arr() As String
Dim arr2() As String
arr = Split(yourCell, char(10))
arr2 = Split("first, second, third", "," )
For i = 1 To UBound(arr)
debug. print arr(i) + arr2(i)
next i
after rebuilding the new string the new string assign it back to the cell
This will only place (random) text after each line in the cell. But it gives you a place to start.
Option Explicit
Public Sub RePrint()
Dim MyRange As Range
Dim MyArray As Variant
Dim i As Long
Set MyRange = Range("A1")
MyArray = Split(MyRange, Chr(10))
For i = LBound(MyArray) To UBound(MyArray)
MyArray(i) = MyArray(i) & " Text" & i
Next i
MyRange = Join(MyArray, Chr(10))
End Sub
you could use this function:
Function AddText(rng As Range, textsArr As Variant) As String
Dim nTexts As Long, nLines As Long, iLine As Long
Dim linesArr As Variant
nTexts = UBound(textsArr) - LBound(textsArr) + 1
With rng
linesArr = Split(.Value, vbLf)
nLines = UBound(linesArr) - LBound(linesArr) + 1
If nTexts < nLines Then nLines = nTexts
For iLine = 1 To nLines
linesArr(LBound(linesArr) - 1 + iLine) = linesArr(LBound(linesArr) - 1 + iLine) & " " & textsArr(LBound(textsArr) - 1 + iLine)
Next iLine
AddText = Join(linesArr, vbLf)
End With
End Function
to be exploited as follows
Option Explicit
Sub main()
Dim cell As Range
Dim additionalTexts As Variant
additionalTexts = Array("First Text", "Second Text", "Third Text", "Fourth Text") '<--| set your array of additional text, each element index corresponding to to be processed cell content line
With Worksheets("ADDTEXT") '<--| reference your relevant worksheet (change "ADDTEXT" to your actual relevant worksheet name)
For Each cell In .Range("A1", .Cells(.Rows.Count, 1).End(xlUp)) '<--| reference its column "A" cells form row 1 down to last not empty row
cell.Value = AddText(cell, additionalTexts) '<--| process
Next cell
End With
End Sub
This will but in the text "First Line", "Second Line"... after each line. The way it is set up now uses the value in A1 and replaces the value in A1. It is ideal for cells with 4 lines or less, but it will work with more.
Sub appendCharacters()
Dim lines() As String
Dim text As String
lines = Split(Range("A1"), Chr(10))
Range("A1").Value = ""
For i = LBound(lines) To UBound(lines)
Select Case i
Case 0
text = " First Line"
Case 1
text = " Second Line"
Case 2
text = " Third Line"
Case 3
text = " Fourth Line"
Case Else
text = " Another Line"
End Select
lines(i) = lines(i) + text
Range("A1").Value = Range("A1").Value + lines(i)
If i <> UBound(lines) Then
Range("A1").Value = Range("A1").Value + vbCrLf
End If
Next i
End Sub
I programmatically add elements from a database to a multicolumn listbox using this code :
Do While (Not rs.EOF)
ExistingSheetsListBox.AddItem
ExistingSheetsListBox.List(i, 0) = rs.Fields(0)
ExistingSheetsListBox.List(i, 1) = rs.Fields(1)
ExistingSheetsListBox.List(i, 2) = rs.Fields(2)
ExistingSheetsListBox.List(i, 3) = rs.Fields(3)
ExistingSheetsListBox.List(i, 4) = rs.Fields(4)
i = i + 1
rs.MoveNext
Loop
The insertion in the listbox works fine, but the column width is not always adapted to the length of the elements inserted in it, I would like to know how I can do so that the column width of each column is adapted to the text inserted into it.
EDIT : I used the solution proposed by #Excel Developers with the piece of code given by #HarveyFrench.
There is no autosize option, following sample code shows 2 ways to do this.
This does not take into account anything other than being a sample.
Class Module clsListCtrlWidths
'class option used so we can use Collection instead of an array.
Option Explicit
Public m_ColWidthMax As Long
Forms Module. Initialise somewhere
Dim l_ColumnWidths As Collection
Set l_ColumnWidths = New Collection
Forms Module functions
Private Function SetColWidth(stLen As String, ctCol1 As control, lPosCol As Long) As String
Dim stWidthTemp As String
If lPosCol > 0 Then
stWidthTemp = stLen & ";"
End If
Dim lTmpWidth As Long
Dim lColWidth As Long
lTmpWidth = ctCol1.Width
ctCol1.AutoSize = True
lColWidth = ctCol1.Width
ctCol1.AutoSize = False
ctCol1.Width = lTmpWidth
If l_ColumnWidths.Count > lPosCol Then
If l_ColumnWidths.Item(lPosCol + 1).m_ColWidthMax < lColWidth Then
l_ColumnWidths.Item(lPosCol + 1).m_ColWidthMax = lColWidth
Else
lColWidth = l_ColumnWidths.Item(lPosCol + 1).m_ColWidthMax
End If
Else
Dim clsColWidth As clsListCtrlWidths
Set clsColWidth = New clsListCtrlWidths
clsColWidth.m_ColWidthMax = lColWidth
l_ColumnWidths.Add clsColWidth
End If
stWidthTemp = stWidthTemp & lColWidth
SetColWidth = stWidthTemp
End Function
Following function takes listbox & calls on above function;
Private Function AutoSizeColsWidth(ByRef ctListCtrl As MSForms.ListBox)
Dim txtBoxDummy As control
Set txtBoxDummy = Me.Controls.Add("Forms.TextBox.1", "txtBoxDummy", False)
txtBoxDummy.AutoSize = True
Dim lRow As Long
Dim lCol As Long
Dim strColWidth As String
For lRow = 0 To ctListCtrl.ListCount - 1
For lCol = 0 To ctListCtrl.ColumnCount - 1
txtBoxDummy = ctListCtrl.List(lRow, lCol)
strColWidth = SetColWidth(strColWidth, txtBoxDummy, lCol)
Next lCol
Next lRow
ctListCtrl.ColumnWidths = strColWidth
End Function
Size Each time you add a single item
'assumes rs.Fields is a control or converted to control
Dim strColWidth As String
strColWidth = SetColWidth(strColWidth, rs.Fields(0), 0)
strColWidth = SetColWidth(strColWidth, rs.Fields(1), 1)
strColWidth = SetColWidth(strColWidth, rs.Fields(2), 2)
strColWidth = SetColWidth(strColWidth, rs.Fields(3), 3)
'etc
ctListCtrl.ColumnWidths = strColWidth
Or size once after adding lot of items
Call AutoSizeColsWidth(myListBox) 'call after completely loading listbox
Added as I was looking for a way to do this & OP is Google's top answer.
You can use the ColumnWidths property to set the size of the columns.
eg `ExistingSheetsListBox.ColumnWidths = "60;60;160;160;60"
For more info see here
I have not found anyway to automatically set the widths depending ont he data in each column, and I am pretty sure such a method does not exist.
Read the width of the existing column and assign it to a variable and use that in the listbox column property.
For Example You have six columns A to F and You need to auto fit the column F
FWidth = Columns("F").ColumnWidth * 7.6
ListBox1.ColumnWidths = "120,120,120,120,120," & FWidth & ""
The Multiply of 7.6 will converts the value to Points.
In Similar Way You can do it for all of Your columns.
Autosize Listbox and Combobox Columns with this function and Optionaly Resize Listbox/Combobox controls themselves.
Function ControlsResizeColumns(LBox As MSForms.Control, Optional ResizeListbox As Boolean)
Application.ScreenUpdating = False
Dim ws As Worksheet
If sheetExists("ListboxColumnWidth", ThisWorkbook) = False Then
Set ws = ThisWorkbook.Worksheets.Add
ws.Name = "ListboxColumnwidth"
Else
Set ws = ThisWorkbook.Worksheets("ListboxColumnwidth")
ws.Cells.Clear
End If
'---Listbox/Combobox to range-----
Dim rng As Range
Set rng = ThisWorkbook.Sheets("ListboxColumnwidth").Range("A1")
Set rng = rng.Resize(UBound(LBox.List) + 1, LBox.ColumnCount)
rng = LBox.List
rng.Characters.Font.Name = UserForm1.ListBox1.Font.Name
rng.Characters.Font.Size = UserForm1.ListBox1.Font.Size
rng.Columns.AutoFit
'---Get ColumnWidths------
rng.Columns.AutoFit
Dim sWidth As String
Dim vR() As Variant
Dim n As Integer
Dim cell As Range
For Each cell In rng.Resize(1)
n = n + 1
ReDim Preserve vR(1 To n)
vR(n) = cell.EntireColumn.Width + 10 'if not some extra space it cuts a bit off the tail
Next cell
sWidth = Join(vR, ";")
Debug.Print sWidth
'---assign ColumnWidths----
With LBox
.ColumnWidths = sWidth
'.RowSource = "A1:A3"
.BorderStyle = fmBorderStyleSingle
End With
'----Optionaly Resize Listbox/Combobox--------
If ResizeListbox = True Then
Dim w As Long
For i = LBound(vR) To UBound(vR)
w = w + vR(i)
Next
DoEvents
LBox.Width = w + 10
End If
'remove worksheet
Application.DisplayAlerts = False
ws.Delete
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Function
Function sheetExists(sheetToFind As String, Optional InWorkbook As Workbook) As Boolean
If InWorkbook Is Nothing Then Set InWorkbook = ThisWorkbook
On Error Resume Next
sheetExists = Not InWorkbook.Sheets(sheetToFind) Is Nothing
End Function
I have a spreadsheet of symbols and matching hex colors. I want to fill the cell itself (or the one next to it) with the hex color within the cell. I've read a bit about "conditional formatting", and I think that's the way to do it.
How might I achieve the result I would like?
Can't be achieved with Conditional Formatting for all colours.
Assuming: Row1 contains Data Labels, data set does not have gaps, the HEX colour is for the fill not the font, you have parsed the HEX colour values (numbers, not formulae) into Columns C:E (R,G,B) and that you do not require to do this often, then the ColourCells macro might suit:
Sub ColourCells()
Dim HowMany As Integer
On Error Resume Next
Application.DisplayAlerts = False
HowMany = Application.InputBox _
(Prompt:="Enter last row number.", Title:="To apply to how many rows?", Type:=1)
On Error GoTo 0
Application.DisplayAlerts = True
If HowMany = 0 Then
Exit Sub
Else
Dim i As Integer
For i = 2 To HowMany
Cells(i, 3).Interior.Color = RGB(Cells(i, 3), Cells(i, 4), Cells(i, 5))
Next i
End If
End Sub
and enter the value you want for n when prompted.
Sample output and formulae etc:
Excel's RGB() function actually creates a BGR value (I don't think anybody that might know why is saying why though) so Excel shows nibbles in reverse order. For the code Columns3,4,5 was logical but BGR rather than the conventional RGB in the image I thought might look odd. For F in the image the C3 value (the LEFT hand column of the 'RGB' three) is derived from applying RIGHT() to the Hex colour.
Minor edit to Jon Peltier's answer. His function ALMOST works, but the colors it renders are incorrect due to the fact the Excel will render as BGR rather than RGB. Here is the corrected function, which swaps the pairs of Hex values into the 'correct' order:
Sub ColorCellsByHex()
Dim rSelection As Range, rCell As Range, tHex As String
If TypeName(Selection) = "Range" Then
Set rSelection = Selection
For Each rCell In rSelection
tHex = Mid(rCell.Text, 6, 2) & Mid(rCell.Text, 4, 2) & Mid(rCell.Text, 2, 2)
rCell.Interior.Color = WorksheetFunction.Hex2Dec(tHex)
Next
End If
End Sub
Much simpler:
ActiveCell.Interior.Color = WorksheetFunction.Hex2Dec(Mid$(ActiveCell.Text, 2))
Mid strips off the leading "#", Hex2Dec turns the hex number into a decimal value that VBA can use.
So select the range to process, and run this:
Sub ColorCellsByHexInCells()
Dim rSelection As Range, rCell As Range
If TypeName(Selection) = "Range" Then
Set rSelection = Selection
For Each rCell In rSelection
rCell.Interior.Color = WorksheetFunction.Hex2Dec(Mid$(rCell.Text, 2))
Next
End If
End Sub
There is no need to repeatedly pierce the VBA/Worksheet barrier to convert. This streamlined version gets the byte order correct:
Sub ColorCellsByHex()
Dim r
If TypeName(Selection) <> "Range" Then Exit Sub
For Each r In Selection
r.Interior.Color = Abs(("&H" & Mid(r, 6, 2) & Mid(r, 4, 2) & Mid(r, 2, 2)))
Next
End Sub
This is another option - it updates the cell color when you select the cell assuming the value in the cell starts with "#" and is 7 characters.
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
If (Left(ActiveCell.Text, 1) = "#" And Len(ActiveCell.Text) = 7) Then
ActiveCell.Interior.Color = WorksheetFunction.Hex2Dec(Mid$(ActiveCell.Text, 2))
End If
End Sub
For this, a userform can be made with the Hex2Dec function.
Function Hex2Dec(n1 As String) As Long
Dim nl1 As Long
Dim nGVal As Long
Dim nSteper As Long
Dim nCount As Long
Dim x As Long
Dim nVal As Long
Dim Stepit As Long
Dim hVal As String
nl1 = Len(n1)
nGVal = 0
nSteper = 16
nCount = 1
For x = nl1 To 1 Step -1
hVal = UCase(Mid$(n1, x, 1))
Select Case hVal
Case "A"
nVal = 10
Case "B"
nVal = 11
Case "C"
nVal = 12
Case "D"
nVal = 13
Case "E"
nVal = 14
Case "F"
nVal = 15
Case Else
nVal = Val(hVal)
End Select
Stepit = (nSteper ^ (nCount - 1))
nGVal = nGVal + nVal * Stepit
nCount = nCount + 1
Next x
Hex2Dec = nGVal
End Function
...
UserForm1.TextBox1 = "RGB(" & Hex2Dec(UserForm1.txtHex1.Value) & "," & _
Hex2Dec(UserForm1.txtHex2.Value) & "," & Hex2Dec(UserForm1.txtHex3.Value) & ")"
For example ;the entered value to textbox: #FF8800 - Result : RGB(255,136,0)