This might be a trivial question for you experts out there:
Based on the input (Week) the table is initially filtered on that specific week(WK) and the next one(WK+1).
I'm then formatting all WK+1 cells to be greyed out.
So far so good. Now the question. How can I change the code below so that the entire row containing a cell with the WK+1 value to be greyed out?
ActiveSheet.Range("B5").AutoFilter Field:=1, Criteria1:=WK, Operator:=xlOr, _
Criteria2:=(WK + 1)
With ActiveSheet.Range("$B:$B").FormatConditions _
.Add(xlCellValue, xlEqual, "=" & WK + 1)
With .Font
.Bold = True
.ColorIndex = 15
End With
End With
Thanks in advance!
Mac
This is possible with FormatCondition of type xlExpression.
Example:
ActiveSheet.Range("$A:$Z").FormatConditions.Delete
ActiveSheet.Range("A1").Activate
With ActiveSheet.Range("$A:$Z").FormatConditions _
.Add(Type:=xlExpression, Formula1:="=($B1=" & WK + 1 & ")")
With .Font
.Bold = True
.ColorIndex = 15
End With
End With
I delete the FormatConditions before I add the new one. Because if not, multiple calls of this code would result in multiple FormatConditions ever with the same condition but possible other values of WK. This is because the code adds a new FormatCondition everytime it runs.
Greetings
Axel
Related
I am very new to Excel, VBA, Macro. My macro was working fine because I gave a simple formula, for example, D2(column name)-C2(column name) = Total time in HH:MM format new column. But I notice for some output is just #### not sure what is wrong. 1).Column)).Formula = _
"=" & cl.Offset(1, 0).Address(0, 0) & "-" & .Cells(2, col1).Address(0, 0)
cl.Offset(, 1).EntireColumn.NumberFormat = "[hh]:mm"
The issue occurs because your date in J is earier than in I and therefore the result is negative. You can use the ABS() function to get the absolute difference as positive value.
Therefore adjust your formula as below:
.Formula = "=ABS(" & cl.Offset(1, 0).Address(0, 0) & "-" & .Cells(2, col1).Address(0, 0) & ")"
You have an incorrect formula in this line:
.Range(cl.Offset(1, 1), .Cells(lastR, cl.Offset(1, 1).Column)).Formula = _
"=" & cl.Offset(1, 0).Address(0, 0) & "-" & .Cells(**2**, col1).Address(0, 0)
Why .Cells(2, col1)? This is always giving you row2 of column 1.
Also, after this line:
If cl.Value = "Full Out Gate at Inland or Interim Point (Destination)_recvd"
Then
Add:
If cl.Offset(0,1).Value = "Response Time" Then Exit For
This will keep you from inserting a new column every time you run the macro.
Try using clear variable names and consistent method for referring to rows and columns.
actCol = col1
recvdCol = cl.Column
responseCol = cl.offset(0,1).Column
.Range(lastR, responseCol).Formula = _
"= Abs(" & .Cells(lastR, recvdCol) & "-" & .Cells(lastR, actCol).Address(0, 0) & ")"
I would use a simpler approach. Highlight the entire table, and click "Format as Table", and be sure to check off "My table has headers." This will give you a named range (default name is Table1, but you can change it). Then, in the Response Time column, simply enter your formula on the first row of the table, but use your mouse to select the cells instead of typing in a cell name like "I2". You will find that the resulting formula includes something like =[#actl]-[#recvd], except that the actl and recvd will be replaced by your actual column names. And, the formula will apply to every row of the table. If you add a new row, the formula will automatically appear in that row. No code needed.
If you have a reason to use code instead of a Table (named ranges), then I would recommend (1) this code be placed directly in the "Main" worksheet module and (2) use use the "Worksheet_Changed" procedure. Microsoft Excel VBA Reference. In this case, any time the
Private Sub Worksheet_Change(ByVal Target As Range)
'Note, Target is the Range of the cell(s) that just changed.
If Intersect(Target, Range("A1:A10")) Is Nothing Or Target.Cells.Count > 1 Then Exit Sub
If ActiveSheet.Cells(1, Target.Column) = "Full Out Gate at Inland or Interim Point (Destination)_actual" Then
' Cell in actual column was modified. Let's set the formula in the Response Time column:
On Error Goto EH
Application.EnableEvents = False
' Add your code here. You'll need to modify it somewhat to accommodate this methodology.
Application.EnableEvents = True
End If
EH:
Application.EnableEvents = True
Err.Raise ' expand this to whatever error you wish to raise
End Sub
Err.Raise help
Using VBA in excel, trying to understand how I can use a checkbox to hide/unhide any row that has a specific value in a specific column. My VBA skills are getting better more I practice but I am still not good with loops just yet. Appreciate any help you can provide. Here is what I have so far.
Private Sub CkBx_ShowAllRecords_Click()
If Me.CkBx_ShowAllRecords = True Then
For Each Row In Range("Table1").ListObject.ListColumns
If Row.Cells(1, "column5").Value = "Submission Complete" Then
Application.EntireRow.Visible=True
Next
End if
End Sub
Additionally when I uncheck the box I would want all rows where column 5 cell value equals "submission complete" would be hidden (just the opposite of what I put above when I check the box control).
Hope this may help you:
Private Sub CkBx_ShowAllRecords_Click()
Dim i As Long
If Me.CkBx_ShowAllRecords = True Then
For i = 1 To ActiveSheet.ListObjects("Table1").Range.Rows.Count
If ActiveSheet.ListObjects("Table1").DataBodyRange(i, 5).Value = "Submission Complete" Then
Rows((i + 1) & ":" & (i + 1)).Select
Selection.EntireRow.Hidden = True
End If
Next i
Else
ActiveSheet.Rows.EntireRow.Hidden = False
End If
Me.Hide
End Sub
My code is checking if cell value from 2 sheets are different, if no it continue check for next row, if different it copy from sheet2 to sheet1 the cell value where I need and add to Cell in sheet1(where the value copied too) a comment with the old value.
every time when the value changed again it remove the comment and put new one.
I need to do a comment check if exist and append the old value to comment.
I want that the comment will contain all the old values that changed in the cell.
this is my piece of code:
If Not IsEmpty(datasheet.Cells(iData, j).Value) Then
comm = user & vbNewLine & "Old Date:" & vbNewLine & ActiveCell.Value
datasheet.Cells(iData, j).Copy Destination:=ActiveCell
With ActiveCell
ActiveCell.Interior.ColorIndex = 0
With ActiveCell.Borders
.LineStyle = xlContinuous 'Setting style of border line
.Weight = xlThin 'Setting weight of border line
.ColorIndex = xlAutomatic 'Setting colour of border line
End With
If Not .Comment Is Nothing Then .Comment.Delete
.ClearComments
.AddComment
.Comment.Text Text:=comm
.Comment.Visible = False
End With
I am currently working on a bear of a worksheet that is designed to show the change of individual parameters over the same time interval using the Backdoor technique detailed at http://peltiertech.com/excel/chartshowto/panelunevenscales.html.
Basically, I have it set up as a template where 5 columns of data (which vary in length of rows) can be pasted into columns A-F starting at row 12. The time column that I would like to filter is in column A and I basically want to make it so that 2 combo boxes (ComboBox1 and ComboBox2) can be used to set an upper and lower time limit and filter out any other data. I'm hoping I can turn this into a dynamic chart that will resize the x-axis to show only the selected time period.
I'm still relatively new to using VBA and I did a good bit of searching and the only thing I could find that seemed related was the question answered at http://www.ozgrid.com/forum/showthread.php?t=54376. I tried the following code and kept getting errors:
Sub TimeFilter()
Crit1 = Format(ComboBox1, "0")
Crit2 = Format(ComboBox2, "0")
.AutoFilterMode = False
.Range("A12:L10000").AutoFilter
.Range("A12:L10000").AutoFilter Field:=1, Criteria:=">=" & crit1, Operator:=xlAnd, Criteria2:="<=" & crit2
End Sub
Any ideas on why it might not be working? Any help or guidance is appreciated!
****EDIT****
Here is the updated FULL code for the spreadsheet I'm using, and with the TimeFilter script I get a "Run-time error '1004', AutoFilter method of Range class failed":
**The time that I am filtering by is in 0.2 second intervals with the format MM:SS.X.
Sub CreateComboBoxes()
Dim Cell As Range
Dim sht As Worksheet
Set sht = ThisWorkbook.Worksheets("Sheet1")
Set Cell = Range("I8")
With Cell
sht.DropDowns.Add(.Left, .Top, .Width, .Height).Name = "ComboBox1"
End With
Set Cell = Range("K8")
With Cell
sht.DropDowns.Add(.Left, .Top, .Width, .Height).Name = "ComboBox2"
End With
End Sub
Sub TimeFilter()
Crit1 = Format(ComboBox1, "0")
Crit2 = Format(ComboBox2, "0")
Worksheets("Sheet1").AutoFilterMode = False
Worksheets("Sheet1").Range("A12:L10000").AutoFilter
Worksheets("Sheet1").Range("A12:L10000").AutoFilter Field:=1,Criteria1:=">=" & Crit1, Operator:=xlAnd, _
Criteria2:="<=" & Crit2
End Sub
I preface this by stating that this is not an answer but an explanation in the use of With, End With statement. The comment section does not offer the formatting tools required to do so properly
The With, End With statements save you on typing the same bits over and over.
ThisWorkbook.Worksheets("Sheet1").UsedRange.Font.ColorIndex = 3
ThisWorkbook.Worksheets("Sheet1").UsedRange.Font.Bold = True
ThisWorkbook.Worksheets("Sheet1").UsedRange.Font.Size = 15
ThisWorkbook.Worksheets("Sheet1").UsedRange.Font.Name = "Times new Roman"
Can also be written as
With ThisWorkbook.Worksheets("Sheet1").UsedRange.Font
.ColorIndex = 3
.Bold = True
.Size = 15
.Name = "Times new Roman"
End With
You'll notice the "." in front of the lines in between the with end with statement, this means it should be read as a continuation of what is set by the With statement.
I am using a loop to put a conditional format in "every 4th row" in "column D". However, I am not able to get the code correct.
I had two seperate things happen. First, I have had the formula show up in the spreadsheet with " " around the formula and the conditional format did not work. So now I am trying to rewrite it using the following code and it tells me compile error expected end of statement.
Any help on how I can get the conditional format of D(i-1)>sum(D(i):D(i+2) shade cell red to work is appreciated.
This is the middle of the For/Next loop where I am trying to shade.
Range("D" & (i - 1)).Select
Selection.FormatConditions.Add Type:=xlExpression, Formula1:="D" & (i-1) & "> Sum(D" & i & "D" & (i + 2)")"
Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
With Selection.FormatConditions(1).Interior
.PatternColorIndex = xlAutomatic
.Color = 255
.TintAndShade = 0
End With
Selection.FormatConditions(1).StopIfTrue = False
i = i + 4
This worked for me:
Sub Tester()
Dim i As Long, fc As FormatCondition
For i = 2 To 10 Step 4
Set fc = ActiveSheet.Range("D" & (i - 1)).FormatConditions. _
Add(Type:=xlExpression, _
Formula1:="=D" & (i - 1) & "> Sum(D" & i & ":D" & (i + 2) & ")")
fc.SetFirstPriority
With fc.Interior
.PatternColorIndex = xlAutomatic
.Color = 255
.TintAndShade = 0
End With
fc.StopIfTrue = False
Next i
End Sub
Is it a requirement to do this in VBA? I'm asking because, through regular conditional formatting, you could also easily apply it to every 4th row.
To do so, you simply need a formula like this one in your conditional formatting:
=AND(MOD(ROW($D5),4)=0, $D5 > SUM($D$2:$D4))
The MOD-function divides the row number by 4 and checks if the remainder is 4.
It's not exactly what you asked for, but it might solve your situation...