Precise informations in text file to excel columns using VBA - vba

[enter link description here][1]I'm trying to search specific words in this text file in order to output it's line content in excel columns. The text file contains multiple sections. I'm able to output the first section of my text file but for some reasons I can't define a loop so I could retrieve every section of the file.
My code so far :
Sub test()
Dim myFile As String, text As String, textline As String, DDC As Integer, DDR As Integer, DDP As Integer, ADC As Integer, i As Integer, SE As Integer, SP As Integer, SG As Integer, j As Integer, v As Integer
myFile = "C:\Users\Seb\Desktop\text2.txt"
Open myFile For Input As #1
Do Until EOF(1)
Line Input #1, textline
text = text & textline
Loop
Close #1
i = 1
DDC = InStr(text, "Date de calcul")
DDR = InStr(text, "Date de retraite")
ADC = InStr(text, "Âge à la date du calcul")
SE = InStr(text, "Service d'emploi")
SP = InStr(text, "Service de participation")
SG = InStr(text, "Salaire gagné")
Cells(i + 1, 1).Value = Mid(text, DDC, 14)
Cells(i + 1, 2).Value = Mid(text, DDC + 36, 10)
Cells(i + 2, 1).Value = Mid(text, DDR, 16)
Cells(i + 2, 2).Value = Mid(text, DDR + 36, 10)
Cells(i + 3, 1).Value = Mid(text, ADC, 23)
Cells(i + 3, 2).Value = Mid(text, ADC + 36, 6)
Cells(i + 4, 1).Value = Mid(text, SE, 16)
Cells(i + 4, 2).Value = Mid(text, SE + 36, 6)
Cells(i + 5, 1).Value = Mid(text, SP, 24)
Cells(i + 5, 2).Value = Mid(text, SP + 36, 6)
For v = 0 To 10
j = v * 228
Cells(v + 7, 1).Value = Mid(text, SG + j, 24) + Mid(text, SG + 64 + j, 10) + "/ " + Mid(text, SG + 77 + j, 10)
Cells(v + 7, 2).Value = Mid(text, SG + 103 + j, 10)
Next v
End Sub
An exemple of my text file is available here: http://txt.do/5j2dq
As I mentioned before, I'm only able to output section 1 in excel. What my code should be in order to retrieve every sections of my text file?

After you have covered each section, simply remove the covered part from your text string, so that in the next iteration e.g. InStr(text, "Date 1") will find the Date 1 line of the next section.
Do While True
DDC = InStr(text, "Date 1")
If DDC = 0 Then
' no more sections - exit loop
Exit Do
End If
DDR = InStr(text, "Date 2")
ADC = InStr(text, "Age")
' ......
Next v
' remove the section that was just handled
text = Mid(text, SG + 30)
Loop

If you bring the TXT file in as Data ► External Data ► From Text, you can set period as an Other delimiter (with Treat consecutive delimiters as one being True).
Sub Import_Text()
Dim c As Long, myFile As String
myFile = "C:\Users\Seb\Desktop\text.txt"
With Worksheets("Sheet9") '<~~set this worksheet reference properly!
With .QueryTables.Add(Connection:="TEXT;" & myFile, _
Destination:=Range("$A$1"))
.Name = "TXT"
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.TextFilePromptOnRefresh = False
.TextFilePlatform = 437
.TextFileStartRow = 1
.TextFileParseType = xlDelimited
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = True
.TextFileTabDelimiter = False
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = False
.TextFileSpaceDelimiter = False
.TextFileOtherDelimiter = "."
.TextFileColumnDataTypes = Array(1, 1)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With
'these will cleanup (trim) the results
For c = 1 To 2
With .Columns(c)
.TextToColumns Destination:=.Cells(1), DataType:=xlFixedWidth, _
FieldInfo:=Array(0, 1), TrailingMinusNumbers:=True
End With
Next c
End With
End Sub
There are two final Range.TextToColumns method with the xlFixedWidth option that simply trim off any rogue leading/railing spaces from the results.

Related

Excel VBA Address comparing output non matching addresses

I am working on a workbook that has three tabs. My Customer list Addresses, Outsource customer listing addresses: and Output No Match:. I am looking to run my list agents an outsource list and if my address list does not match any addresses on the out source list. It outputs on the No match tab.
I have built a working document but it is so slow and feel someone here could really help point me in the right direction.
All three sheets column headers ("Customer Name","Address 1","Address 2","City","State","Zip Code")
I am using a code similar to the one below to find none matches on all the columns. It only looks at the first few characters in hope to speed things up but i am getting no where fast.
I am running it on a loop somewhat like this which seems to be very incessant and slow when comparing addresses agent 200,000 records.
For I = 2 To LastRow
If Left(UCase(Trim(wsAddressS_1.Cells(1 + I, 6).Value)), 5) =
Left(UCase(VLookLike(wsAddressS_1.Cells(1 + I, 6).Value, wsAddressS_2.Range("F1:F" & LastRow2 + 10))), 5) Then
Match_Zip = "Match"
Else
Match_Zip = "No Match"
End If
If strMatchZip <> "Match" Then
LastRow1 = wsAddressS_4.Range("F" & Rows.Count).End(xlUp).Row
wsAddressS_4.Cells(LastRow4 + 1, 1).Value = wsAddressS_1.Cells(1 + I, 1).Value
wsAddressS_4.Cells(LastRow4 + 1, 2).Value = wsAddressS_1.Cells(1 + I, 2).Value
wsAddressS_4.Cells(LastRow4 + 1, 3).Value = wsAddressS_1.Cells(1 + I, 3).Value
wsAddressS_4.Cells(LastRow4 + 1, 4).Value = wsAddressS_1.Cells(1 + I, 4).Value
wsAddressS_4.Cells(LastRow4 + 1, 5).Value = wsAddressS_1.Cells(1 + I, 5).Value
wsAddressS_4.Cells(LastRow4 + 1, 6).Value = wsAddressS_1.Cells(1 + I, 6).Value
End If
Sleep 10
DoEvents
Next I
e.g VLookLike
Private Function VLookLike(txt As String, rng As Range) As String
Dim temp As String, e, n As Long, a()
Static RegX As Object
If RegX Is Nothing Then
Set RegX = CreateObject("VBScript.RegExp")
With RegX
.Global = True
.IgnoreCase = True
.Pattern = "(\S+).*" & Chr(2) & ".*\1"
End With
End If
With RegX
For Each e In rng.Value
If UCase$(e) = UCase(txt) Then
VLookLike = e
Exit For
End If
temp = Join$(Array(e, txt), Chr(2))
If .test(temp) Then
n = n + 1
ReDim Preserve a(1 To 2, 1 To n)
a(2, n) = e
Do While .test(temp)
a(1, n) = a(1, n) + Len(.Execute(temp)(0).submatches(0))
temp = Replace(temp, .Execute(temp)(0).submatches(0), "")
Loop
End If
Next
End With
If (VLookLike = "") * (n > 0) Then
With Application
VLookLike = .HLookup(.Max(.Index(a, 1, 0)), a, 2, False)
End With
End If
End Function
Any help or suggestions would be much appreciated!
I haven't read all the code, sorry, but I have had problems on comparing strings. Perhaps it would work if you tell vba that you are gonna compare 2 strings. You could use the function Cstr() for example
CStr(Left(UCase(StrAddress), 3)) = CStr(Left(UCase(VLookLike(StrAddress, rng2)), 3))

Proceed to next empty cell if a condition is met

I have a sheet with Item names in the firs row.
I am using a Forloop to pass trough the cells in row 1 - i.
I use the value content of each cell to import a column from a .CSV file in the corresponding cell below it in row 2, by using j for that.
However, I have some .CSV files that are missing and I need to move on to the next cell in row 2, while moving on to the next cell in row 1. Basically skipping a column.
What I have so far is:
Dim FSO As Object
Dim Folder As Object
Dim File As String
Set FSO = CreateObject("Scripting.FileSystemObject")
Set Folder = FSO.GetFolder("C:\Users\Betty\AppData\Roaming\MetaQuotes\Terminal\B4D9BCD10BE9B5248AFCB2BE2411BA10\MQL4\Files")
For i = 2 To HCP.Cells(1, HCP.Columns.Count).End(xlToLeft).Column
Item = HCP.Cells(1, i).Value
FilePath = Folder & "\" & Item & "1440.CSV"
If Item = "" Or Dir(FilePath) = "" Then GoTo Continue
j = HCP.Cells(2, HCP.Columns.Count).End(xlToLeft).Column
With HCP.QueryTables.Add(Connection:="TEXT;" & FilePath, Destination:=HCP.Cells(2, j + 1))
.TextFileParseType = xlDelimited
.TextFileCommaDelimiter = True
.TextFileSpaceDelimiter = True
.TextFileColumnDataTypes = Array(9, 9, 9, 9, 9, 1, 9, 9, 9, 9)
.Refresh BackgroundQuery:=False
End With
Continue:
Next
I need the column index of j to be corresponding to the column index of i at all times.
I would avoid using GoTo Continue. Just check the negative of your statements before entering the loop. You are also missing some End If statement in both your question and solution.
I left comments showing where the code will skip to if either Item or Dir are blank. Same result, just cleaner code.
For i = 2 To HCP.Cells(1, HCP.Columns.Count).End(xlToLeft).Column
Item = HCP.Cells(1, i).Value
FilePath = Folder & "\" & Item & "1440.CSV"
If Item <> "" Or Dir(FilePath) <> "" Then 'Test Here
j = HCP.Cells(2, HCP.Columns.Count).End(xlToLeft).Column
If j <> i Then j = i
With HCP.QueryTables.Add(Connection:="TEXT;" & FilePath, Destination:=HCP.Cells(2, j))
.TextFileParseType = xlDelimited
.TextFileCommaDelimiter = True
.TextFileSpaceDelimiter = True
.TextFileColumnDataTypes = Array(9, 9, 9, 9, 9, 1, 9, 9, 9, 9)
.Refresh BackgroundQuery:=False
End With
End If 'Skips to here if either are blank.
Next i
I figured it out. This is what I am using now.
For i = 2 To HCP.Cells(1, HCP.Columns.Count).End(xlToLeft).Column
Item = HCP.Cells(1, i).Value
FilePath = Folder & "\" & Item & "1440.CSV"
If Item = "" Or Dir(FilePath) = "" Then GoTo Continue
j = HCP.Cells(2, HCP.Columns.Count).End(xlToLeft).Column
If j <> i Then j = i
With HCP.QueryTables.Add(Connection:="TEXT;" & FilePath, Destination:=HCP.Cells(2, j))
.TextFileParseType = xlDelimited
.TextFileCommaDelimiter = True
.TextFileSpaceDelimiter = True
.TextFileColumnDataTypes = Array(9, 9, 9, 9, 9, 1, 9, 9, 9, 9)
.Refresh BackgroundQuery:=False
End With
Continue:
Next
And this is the result:
Please, feel free to make any other suggestions.
Solution 3: Nested ForLoop with Nested IfStatement
For i = 1 To BS.Cells(1, BS.Columns.Count).End(xlToLeft).Column
For j = 1 To BS.Cells(2, BS.Columns.Count - 1).End(xlToLeft).Column
Item = BS.Cells(1, i).Value
FilePath = Folder & "\" & Item & "1440.CSV"
If ((Item <> "") Or (Dir(FilePath) <> "") And (i = j)) Then
With BS.QueryTables.Add(Connection:="TEXT;" & FilePath, Destination:=BS.Cells(2, j + 1))
.TextFileParseType = xlDelimited
.TextFileCommaDelimiter = True
.TextFileSpaceDelimiter = True
.TextFileColumnDataTypes = Array(9, 9, 9, 9, 9, 1, 9, 9, 9, 9)
.Refresh BackgroundQuery:=False
End With
End If
Next j
Next i
Solution 2: Nested Do Loop
Avoiding the "Continue" command, as it is not a VBA command.
For i = 2 To BS.Cells(1, BS.Columns.Count).End(xlToLeft).Column: Do
Item = BS.Cells(1, i).Value
FilePath = Folder & "\" & Item & "1440.CSV"
If Item = "" Or Dir(FilePath) = "" Then Exit Do
j = BS.Cells(2, BS.Columns.Count).End(xlToLeft).Column
If j <> i Then j = i
With BS.QueryTables.Add(Connection:="TEXT;" & FilePath, Destination:=BS.Cells(2, j))
.TextFileParseType = xlDelimited
.TextFileCommaDelimiter = True
.TextFileSpaceDelimiter = True
.TextFileColumnDataTypes = Array(9, 9, 9, 9, 9, 1, 9, 9, 9, 9)
.Refresh BackgroundQuery:=False
End With
Loop While False: Next i
Please, Notice the : Do at the end of the end of the For i.
If one of the following conditions, i.e. Item = "" or Dir(FilePath) = "" is False , then the Do loop is exited. True if the Loop While False: Next i condition for the Do loop is stated.
The two conditions may also be presented as:
For i = 2 To BS.Cells(1, BS.Columns.Count).End(xlToLeft).Column: Do
If Item <> "" Or Dir(FilePath) <> "" Then
'Do something...
Else: Exit Do
End If
Loop While True: Next i
Having the Or condition in the If Item = "" Or Dir(FilePath) = "" Then Exit Do is mandatory as i may be Value <> " ", but the FilePath to the file may be non-existent i.e. Dir(FilePath) = " ", which will spit out an error as the previous I had.
The If j <> i Then j = i in this case is mandatory, as the For i is stated as =2 To, meaning that the loop starts from column 2.
This can be avoided by stating the For i loop as For i = 1 To. However this was the initial loop to get the job done.
Further j can be stated as j = BS.Cells(2, i), obtaining the value of i for a column index.
However, the If j <> i Then j = i statement is advisable for further assurance purposes.
In further search more solutions emerged.
See Solution 3: Nested For Loop with Nested If Statement

VBA Userform user signature input into spreadsheet

I'm new to InkPicture but I like to use it for user to put signature into the form.
I can't seem to save the signature (inkpicture) to the spreadsheet it just inputs it as 0 into the cell I specify.
With UserForm1.InkPicture1.InkEnabled = False Set.Ink
Me.InkPicture1.Ink
.InkEnabled = True End With
lrDep = Sheets("Deploy").Range("A" & Rows.Count).End(xlUp).Row Sheets("Deploy").Cells(lrDep + 1, "A").Value = TBox1.Text Sheets("Deploy").Cells(lrDep + 1, "B").Value = TBox2.Text Sheets("Deploy").Cells(lrDep + 1, "C").Value = TBox3.Text Sheets("Deploy").Cells(lrDep + 1, "D").Value = TBox4.Text
Sheets("Deploy").Cells(lrDep + 1, "G").Value = InkPicture1.Ink
Could someone please help me.
Thank you.
This is not a complete answer but will help you on your way, comment if you have any questions.
First you will have to have a text box on your form that requires the asset ID,
this will have to be amended to match your current form.
Dim RowN As Long
Dim SearchTxt
SearchTxt = TextBox1.Value 'This should be set to the text box name on the form of the asset ID
On Error Resume Next
RowN = Application.WorksheetFunction.Match(SearchTxt, Range("A:A"), 0)
On Error GoTo 0
If RowN > 0 Then
'your code here if matches
MsgBox RowN ' display the row number
Else
'your code here if no match, possibly add new row of data
MsgBox "No match found"
End If
Now you can amend each line of code to use the found row number, for example:
Sheets("Data").Cells("A" & RowN).Value = TextBox1.Txt
If I was creating this form, I would add a search button to check the asset ID and where it finds a match, all the text boxes would then be populated with the current values of the data, these can then be amended before adding back to the sheet.
The following will look for the ID in Column A and if found will use that row to enter the data, this assumes that the ID is stored in TextBox1.Text, amend as required:
Private Sub SB1_Click()
Dim lrREG As Long, lrB As Long, lrDep As Long, lrDis As Long, lrDAT As Long
Dim foundID As Range
Set foundID = Sheets("Data").Range("A:A").Find(What:=TextBox1.Text, Lookat:=xlWhole)
If Not foundID Is Nothing Then
Sheets("Data").Cells(foundID.Row, "A").Value = TextBox1.Text
Sheets("Data").Cells(foundID.Row, "B").Value = TextBox2.Text
Sheets("Data").Cells(foundID.Row, "C").Value = TextBox3.Text
Else
lrDAT = Sheets("Data").Range("A" & Rows.Count).End(xlUp).Row + 1
Sheets("Data").Cells(lrDAT, "A").Value = TextBox1.Text
Sheets("Data").Cells(lrDAT, "B").Value = TextBox2.Text
Sheets("Data").Cells(lrDAT, "C").Value = TextBox3.Text
End If
lrREG = Sheets("Register").Range("A" & Rows.Count).End(xlUp).Row
Sheets("Register").Cells(lrREG + 1, "A").Value = TextBox1.Text
Sheets("Register").Cells(lrREG + 1, "B").Value = TextBox2.Text
Sheets("Register").Cells(lrREG + 1, "C").Value = TextBox3.Text
lrB = Sheets("Built").Range("A" & Rows.Count).End(xlUp).Row
Sheets("Built").Cells(lrB + 1, "A").Value = TB1.Text
Sheets("Built").Cells(lrB + 1, "B").Value = TB2.Text
Sheets("Built").Cells(lrB + 1, "C").Value = TB3.Text
Sheets("Built").Cells(lrB + 1, "D").Value = TB4.Text
Sheets("Built").Cells(lrB + 1, "E").Value = TB5.Text
Sheets("Built").Cells(lrB + 1, "F").Value = TB6.Text
lrDep = Sheets("Deploy").Range("A" & Rows.Count).End(xlUp).Row
Sheets("Deploy").Cells(lrDep + 1, "A").Value = TBox1.Text
Sheets("Deploy").Cells(lrDep + 1, "B").Value = TBox2.Text
Sheets("Deploy").Cells(lrDep + 1, "C").Value = TBox3.Text
Sheets("Deploy").Cells(lrDep + 1, "D").Value = TBox4.Text
Sheets("Deploy").Cells(lrDep + 1, "E").Value = TBox5.Text
Sheets("Deploy").Cells(lrDep + 1, "F").Value = TBox6.Text
lrDis = Sheets("Dispose").Range("A" & Rows.Count).End(xlUp).Row
Sheets("Dispose").Cells(lrB + 1, "A").Value = TextBo1.Text
Sheets("Dispose").Cells(lrDis + 1, "B").Value = TextBo2.Text
Sheets("Dispose").Cells(lrDis + 1, "C").Value = TextBo3.Text
Sheets("Dispose").Cells(lrDis + 1, "D").Value = TextBo4.Text
Sheets("Dispose").Cells(lrDis + 1, "E").Value = TextBo5.Text
Sheets("Dispose").Cells(lrDis + 1, "F").Value = TextBo6.Text
End Sub

Add Check Boxes to a userform with multiple sections that will input a number located on Sheet

I am new to VBA, and I am working on a userform, which was created by someone else. The userform has four areas(Cost Code1, Cost Code 2, exc...) that input information(Cost Code, Truck Rent, Regular Hours and Overtime Hours) into specific columns on the worksheet. Right now there are text boxes at the top of the form that enters the employee name, job number and date with all of the information.
The new project has two job numbers, so instead of using the Job Number Text Box at the top, I need to add Option Buttons, or Check Boxes (whichever is easier) to choose between the two different job numbers for the four groups of information. I would like to only be allowed to select one job number per area on the userform. The job numbers will be located on a second tab called Employees in cells H1 and K1. I need the job number to be entered in column number 4. What is the code for the Check Boxes, or Option Buttons, and where would I enter it in the original code? I appreciate any help.
Private Sub cbOK_Click()
Dim NextRow As Long
'Variable for cycling through cell input
Dim i As Long
Dim Userdate As Date
i = 1
Set EESheet = ActiveWorkbook.Sheets("Employees")
Set TLISheet = ActiveWorkbook.Sheets("Worksheet")
'Activate Worksheet Tab
Sheets("Worksheet").Activate
'Set Autocalc off to speed things up.
Application.Calculation = xlCalculationManual
'Error Handling, go to bad.
On Error GoTo Bad
Userdate = tbDate.Value
'Transfer the data to the rows
For i = 1 To 6
NextRow = Application.WorksheetFunction.CountA(Range("A:A")) + 1
If Me.Controls("tbCC" & i & "RegHrs").Value <> "" Then
Cells(NextRow, 1) = tbDate.Value
Cells(NextRow, 2) = cmbEmployeeName.Value
Cells(NextRow, 3) = Application.WorksheetFunction.VLookup(cmbEmployeeName.Value, EESheet.Range("A:B"), 2, False)
Cells(NextRow, 4) = tbJobNumber.Value
Cells(NextRow, 5) = Me.Controls("tbJobExtra" & i).Value
Cells(NextRow, 6) = Me.Controls("cmbCC" & i).Value
Cells(NextRow, 7) = Application.WorksheetFunction.VLookup(cmbEmployeeName.Value, EESheet.Range("A:C"), 3, False)
Cells(NextRow, 8) = Application.WorksheetFunction.VLookup(cmbEmployeeName.Value, EESheet.Range("A:D"), 4, False)
Cells(NextRow, 10) = Application.WorksheetFunction.VLookup(cmbEmployeeName.Value, EESheet.Range("A:E"), 5, False)
If EEtype = 1 Then
Cells(NextRow, 9) = "SOH"
Else
Cells(NextRow, 9) = "REG"
End If
Cells(NextRow, 10) = Me.Controls("tbCC" & i & "RegHrs").Value
End If
If Me.Controls("tbCC" & i & "OTHrs").Text <> "" Then
NextRow = Application.WorksheetFunction.CountA(Range("A:A")) + 1
Cells(NextRow, 1) = tbDate.Value
Cells(NextRow, 2) = cmbEmployeeName.Value
Cells(NextRow, 3) = Application.WorksheetFunction.VLookup(cmbEmployeeName.Value, EESheet.Range("A:B"), 2, False)
Cells(NextRow, 4) = tbJobNumber.Value
Cells(NextRow, 5) = Me.Controls("tbJobExtra" & i).Value
Cells(NextRow, 6) = Me.Controls("cmbCC" & i).Value
Cells(NextRow, 7) = Application.WorksheetFunction.VLookup(cmbEmployeeName.Value, EESheet.Range("A:C"), 3, False)
Cells(NextRow, 8) = Application.WorksheetFunction.VLookup(cmbEmployeeName.Value, EESheet.Range("A:D"), 4, False)
Cells(NextRow, 9) = "OVT"
Cells(NextRow, 10) = Me.Controls("tbCC" & i & "OTHrs").Value
End If
If i + 1 = 7 Then Exit For
If Me.Controls("cmbCC" & i + 1).Value = "" Then Exit For
Next
Bad:
If Err.Number = 1004 Then
MsgBox "This EE Does Not Exist or You Typed Their Name Incorrectly. Check the EE name spelling or enter the EE into the Employees Tab."
NextRow = Application.WorksheetFunction.CountA(Range("A:A"))
Rows(NextRow).Delete
EEpayrollentry.Hide
Sheets("Employees").Activate
End If
i = 1
For i = 1 To 6
cmbEmployeeName.Value = ""
Me.Controls("tbJobExtra" & i).Text = ""
Me.Controls("cmbCC" & i).Text = ""
Me.Controls("tbCC" & i & "RegHrs").Text = ""
Me.Controls("tbCC" & i & "OTHrs").Text = ""
Next
EEpayrollentry.lbTotalHours.Caption = 0
End Sub

How to change default colors used in VBA code/Macro result (Red, Green)

I am using the following VBA code to change the color of the rows in my spreadsheet every time the value in Column A changes (So that all entries with the same value in column A will be grouped by color. The spreadsheet is sorted by column A already so the items are already grouped, I just needed them colored).
Anyway, when I run this macro the rows are colored red & green (which are very bright and overwhelming colors for this purpose). I need something more subtle..
How do I change this? Or can I specify in my VBA code for it to use certain colors by rgb or color index? {I am using Excel 2007}
Sub colorize()
Dim r As Long, val As Long, c As Long
r = 1
val = ActiveSheet.Cells(r, 1).Value
c = 4
For r = 1 To ActiveSheet.Rows.Count
If IsEmpty(ActiveSheet.Cells(r, 1).Value) Then
Exit For
End If
If ActiveSheet.Cells(r, 1).Value <> val Then
If c = 3 Then
c = 4
Else
c = 3
End If
End If
ActiveSheet.Rows(r).Select
With Selection.Interior
.ColorIndex = c
.Pattern = xlSolid
End With
val = ActiveSheet.Cells(r, 1).Value
Next
End Sub
Run this program (credits here)
Sub colors56()
'57 colors, 0 to 56
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual 'pre XL97 xlManual
Dim i As Long
Dim str0 As String, str As String
For i = 0 To 56
Cells(i + 1, 1).Interior.ColorIndex = i
Cells(i + 1, 1).Value = "[Color " & i & "]"
Cells(i + 1, 2).Font.ColorIndex = i
Cells(i + 1, 2).Value = "[Color " & i & "]"
str0 = Right("000000" & Hex(Cells(i + 1, 1).Interior.Color), 6)
'Excel shows nibbles in reverse order so make it as RGB
str = Right(str0, 2) & Mid(str0, 3, 2) & Left(str0, 2)
'generating 2 columns in the HTML table
Cells(i + 1, 3) = "#" & str & "#" & str & ""
Cells(i + 1, 4).Formula = "=Hex2dec(""" & Right(str0, 2) & """)"
Cells(i + 1, 5).Formula = "=Hex2dec(""" & Mid(str0, 3, 2) & """)"
Cells(i + 1, 6).Formula = "=Hex2dec(""" & Left(str0, 2) & """)"
Cells(i + 1, 7) = "[Color " & i & ")"
Next i
done:
Application.Calculation = xlCalculationAutomatic 'pre XL97 xlAutomatic
Application.ScreenUpdating = True
End Sub
Output sample:
You can customize the colors palette by code, I think the page here will answer your question:
http://www.databison.com/index.php/excel-color-palette-and-color-index-change-using-vba/
Sub change_palette_color
dim color_index as long
color_index = 10
ActiveWorkbook.Colors(color_index) = RGB(128, 128, 128)
End sub
It turns out all I had to do is change a few numbers in the code i posted in my question. I bolded the numbers I had to change. These numbers correspond to the color ID (like what Belisarious put). NOTE: I had to put apostrohpes so that the VBA code wouldn't be recognized as VBA code (because if it is it won't bold the numbers). See the original question for the correct code.
Dim r As Long, val As Long, c As Long
'r = 1
'val = ActiveSheet.Cells(r, 1).Value
'c = 4
'For r = 1 To ActiveSheet.Rows.Count
If IsEmpty(ActiveSheet.Cells(r, 1).Value) Then
Exit For
End If
' If ActiveSheet.Cells(r, 1).Value <> val Then
If c = 3 Then
c = 4
Else
c = 3
End If
End If
ActiveSheet.Rows(r).Select
With Selection.Interior
.ColorIndex = c
.Pattern = xlSolid
End With
val = ActiveSheet.Cells(r, 1).Value
Next
End Sub