When I enter a second date in a cell, I want the initial date to be strikethrough and keep the both date in the same cell
I have a range of cells from column E to H, in which each cell has date.
Your help would be highly appreciated
Sub ColorMeElmo()
'
Dim count As Long
count = ActiveSheet.Cells(Rows.count, "D").End(xlUp).Row
'
Dim i As Long, r1 As Range, r2 As Range
For i = 2 To count
Set r1 = Range("D" & i)
Set r2 = Range("E" & i)
Dim diff1 As Long
diff1 = DateDiff("D", r2.Value, r1.Value)
If diff1 <= 5 Then r2.Interior.Color = vbRed
If diff1 > 5 Then r2.Interior.Color = vbYellow
Next i
For ii = 2 To count
Set r1 = Range("D" & ii)
Set r2 = Range("F" & ii)
Dim diff2 As Long
diff2 = DateDiff("D", r2.Value, r1.Value)
If diff2 <= 5 Then r2.Interior.Color = vbRed
If diff2 > 5 Then r2.Interior.Color = vbYellow
End Sub
Range will change from D, E, F, G, H. But here I give only E
Assuming your dates are already recognized as dates by Excel, you could use the following procedure:
Sub StrikethroughAndNewDate(ByRef rng As Range, ByVal NewDate As Date)
'You can change this value if you need a different date format
Const DateFormat As String = "YYYY-MM-DD"
'Combine dates
rng.Value2 = Format(rng.Value2, DateFormat) & " " & Format(NewDate, DateFormat)
'Add Formatting
rng.Characters(Start:=1, Length:=Len(Format(rng.Value2, DateFormat))).Font.Strikethrough = True
End Sub
Which would give you something like this :
If your dates are both stored as string inside the cells, you could do a simple concatenation instead:
Sub StrikethroughAndNewDate2(ByRef rng As Range, ByVal NewDate As Variant)
'Combine dates
rng.Value2 = rng.Value2 & " " & NewDate
'Add Formatting
rng.Characters(Start:=1, Length:=Len(rng.Value2)).Font.Strikethrough = True
End Sub
Related
I have a date in cell A1 for example: 12/08/22
I want create a list with all days of the month (1-31) in column E using the month and year of the cell A1 as parameter.
Sub TESTEEEEEEE()
Dim r As Range, i As String, j As Long
i = Range("A1").Offset(0, 1).Value = Left(cell.Value, 3)
'k = ????
j = 31
For Each r In Range("E1:E31")
r.NumberFormat = "#"
r.Value = Format(DateSerial(k, i, j), "dd/m/yy")
j = j + 1
Next r
End Sub
I'm stucked in how to extract the the month and year. I was trying using the position of the characteres as parameter, but i'm not getting it work.
i should extract the 4,5 and characterer returning 08 (ok, the code is wrong i was making some tests).
k should extract the 7,8 charachter returning 22.
Someone can help me?
Please, try using the next way. It does not need iteration:
Sub testCreateWholeMonth()
Dim D As Date, lastD As Long
D = Range("A1").value
lastD = Day(WorksheetFunction.EoMonth(DateSerial(Year(D), Month(D), 1), 0))
With Range("E1:E" & lastD)
.value = Evaluate("date(" & Year(D) & "," & Month(D) & ",row(1:" & lastD & "))")
.NumberFormat = "mm.dd.yyyy"
End With
End Sub
You are probably after calendar functions like YEAR, MONTH, EOMONTH
Sub DebugDate()
Dim rg As Range
Set rg = Range("A1") ' should contain a date
Dim dt As Date
dt = rg.Value
Debug.Print Year(dt), Month(dt), CDate(WorksheetFunction.EoMonth(dt, 0))
' End of month not using worksheet function EOMONTH
Debug.Print DateSerial(Year(dt), Month(dt) + 1, 1) - 1
End Sub
Further reading on How to create a calendar with VBA
So I have a list of dates that I am trying to search through and check if they need to be corrected or not. The yellow highlighted cells are examples of changes needed to be made. Wether the date needs fixing or not I want the result of the code to place it in the "Date Fixed" column as shown in the first cell. If the date is not listed as the 30/31st of a month or the 1st then I need to change the day part of the date to either the beginning or end of the month. I have written what I thought would work but I keep receiving a Run Time Error 11 code. Any ideas on how to fix this and keep going through all the dates?
Private Sub FormatDate_Click()
Dim myrow As Integer
Dim startrow As Integer
Dim Dates As Date
Dim Datesfixed As Date
Dim dateTwo As Date
Dim dateEnd As Date
myrow = 2
startrow = 2
Dates = Cells(myrow, 2)
Datesfixed = Cells(myrow, 3)
dateTwo = mm / 1 / yyyy
dateEnd = mm / 31 / yyyy
Do Until Cells(myrow, 1) = ""
If Dates = dateTwo Or dateEnd Then
Datesfixed = Dates
ElseIf Dates <> dateTwo Or dateEnd Then
Dates = dateTwo
myrow = myrow + 1
End If
myrow = myrow + 1
Loop
myrow = 2
startrow = 2
End Sub
Try something like this:
Private Sub FormatDate_Click()
Dim c As Range, dt, d As Long, m As Long, y As Long, dLast As Long
Set c = ActiveSheet.Range("B2") 'first date
Do While Len(c.Value) > 0
dt = c.Value
d = Day(dt) 'extract the parts of the date
m = Month(dt)
y = Year(dt)
dLast = Day(DateAdd("m", 1, DateSerial(y, m, 1)) - 1) 'last day of the month
If d <> 1 And d <> dLast Then
c.Offset(0, 1) = DateSerial(y, m, dLast) 'set to last day of the month
End If
Set c = c.Offset(1, 0) 'next date
Loop
End Sub
I have a problem I hope I can get some help with. In a summary report I need to use date criterias: today's date compared to months in B1:M1 (all cells are date formatted using a userdefined date format to only display the monthname) to sum the rows of data only if an account number is listed in column A. (pls. see below example)
I.E. if todays date is Feb. 7th the VBA code should loop through all rows and only sum the numbers for January and february where an account # is present (it must be in VBA)
Here is what I have so far:
Sub Test()
Dim today, lastdayinmonth As Date
Dim i, ii As Integer
Dim months As Range
today = DateSerial(Year(Date), Month(Date), Day(Date))
lastdayinmonth = DateSerial(Year(Date), Month(Date) + 1, 0)
months = Sheet2.Range("B2:M2")
If idag <= lastdayinmonth Then
For i = 3 To 20
If Not IsEmpty(Sheet2.Range("B" & i)) Then
End If
Next ii
End If
End Sub
Try this code, please. It works based on the assumption that your columns header are Date formatted (no matter if they show only month...), and the sum will be returned in Imediate Window:
Sub TestSumMonth()
Dim arrM As Variant, i As Long, j As Long
Dim nSum As Long, lastRow As Long, sh As Worksheet
Set sh = sheet2
lastRow = sh.Range("A" & sh.Rows.count).End(xlUp).Row
arrM = sh.Range("A1:M" & lastRow).Value
sh.Range("O2:O" & lastRow).Interior.ColorIndex = xlNone ' clear the existing interior color
For i = 1 To UBound(arrM, 1)
If arrM(i, 1) <> Empty Then
nSum = 0
For j = 2 To UBound(arrM, 2)
If Month(Date) >= Month(arrM(1, j)) Then
nSum = nSum + arrM(i, j)
If Month(Date) = Month(arrM(1, j)) Then
With sh.Range("O" & i)
.Value = nSum
.Interior.Color = vbYellow ' interior colored in yellow
End With
Exit For
End If
End If
Next j
End If
Next i
End Sub
The code firstly clears "O:O" range interior color, then returns the sum on the appropriate row of this column and colors the cell interior in yellow...
Now, it would summarize all the passed month values plus the active month.
Excelfile
Hello I have an excel files with time stamps in a row as shown in the image
I want to calculate the difference and enter the value in a new column. I tried the following code but it shows a type mismatch error and I don't know why.
I know its easy, but I'm new to VBA so please help me.
\\Sub macro1()
Dim i As Integer
Dim j As Integer
Dim k As Integer
i = 1
j = 2
k = 2
Do While Cells(i, 1).Value <> ""
Cells(k, 2).Value = Cells(j, 1).Value - Cells(i, 1).Value
i = i + 1
j = i + 1
k = i
Loop
End Sub
Your format (2.10.2017 08:08:30) should be manipulated before using CDate to convert the cell value into a date, then use the VBA function DateDiff. See below. Put =timeDiff(A2,A1) in B2, then copy to B3 and down. Below is the VBA code.
Public Function transformCellStrInDate(ByVal rng As Range) As Date
Dim splitArr As Variant, dateArr As Variant, dateStr As String
splitArr = Split(Trim(rng.Value))
dateArr = Split(splitArr(0), ".")
dateStr = dateArr(0) & "/" & dateArr(1) & "/" & dateArr(2) & " " & splitArr(1)
transformCellStrInDate = CDate(dateStr)
Erase dateArr: Erase splitArr
End Function
Public Function timeDiff(ByVal rngY As Range, ByVal rngX As Range) As Long
timeDiff = DateDiff("n", transformCellStrInDate(rngX), transformCellStrInDate(rngY)) / 60 ' in Hours
End Function
I have this dates from DB and I want to fix the date in VBA excel because excel switch the date with month when filter the column
27/08/2018
31/08/2018
12/9/2018
2/8/2018 wrong date reported at filter in excel need 02/08/2018
6/8/2018 wrong date reported at filter in excel need 06/08/2018
13/08/2018
17/08/2018
20/08/2018
20/08/2018
I have tried this
For i = 2 To lastRow
Dim fDate As Date
Dim dayF As String
Dim monthF As String
Dim yearF As String
Set r = Cells(i, Column_DateStamp)
strDate = Split(r.Text, "/")
dayF = CStr(Format(strDate(0), "00"))
monthF = CStr(Format(strDate(1), "00"))
yearF = CStr(Format(strDate(2), "0000"))
fDate = Format(DateSerial(strDate(2), CStr(Format(strDate(1), "00")), CStr(Format(strDate(0), "00"))), "dd/mm/yyyy")
r.Clear
r.Value = fDate
Next i
The date formats do not match your local date format and as such Excel is trying to convert.
You need to either put the date in and format it appropriately or make the cell text so excel does not try to convert.
Dim i As Long
For i = 2 To lastRow
Dim fDate As Date
Dim r As Range
Set r = Cells(i, Column_DateStamp)
strDate = Split(r.Text, "/")
fDate = DateSerial(strDate(2), strDate(1), strDate(0))
r.Clear
'True date - comment out if you want string
r.NumberFormat = "dd/mm/yyyy"
r.Value2 = fDate
'String - Uncomment if you want string
' r.NumberFormat = "#"
' r.Value2 = Format(fDate, "dd/mm/yyyy")
Next i
Examining your screenshot, the problem is consistent with your Windows Regional Settings being MDY and the Database settings being DMY. This will always result in incorrect action by Excel.
Whoever wrote the ERP application should be able to make the change to input, to Excel, an unambiguous date format; or trigger the excel text import wizard at the time of import.
You can try this macro in the meantime. It should work, but read the notes carefully for possible pitfalls:
Option Explicit
Sub ConvertDates()
'converts dates that have been mismatched MDY / DMY
'Assumes dates are all in selected column
' Only need to select a single cell in the column
' will place results in a column next to original data
' If adjacent column is not blank, a column will be inserted
'Figures out the original format by analyzing a "text" date
'Time components are converted directly. This might be OK unless
' in a non standard format such as 1400Z
Dim R As Range, C As Range
Dim sDelim As String
Dim FileDateFormat As String * 3
Dim i As Long, j As Long, V As Variant
Dim vDateParts As Variant
Dim YR As Long, MN As Long, DY As Long
Dim TM As Double
Dim vRes As Variant 'to hold the results of conversion
Set R = Selection
'Test that selected cell contains a date
If Not IsDate(R(1)) Then
MsgBox "Select a cell containing a date"
Exit Sub
End If
Set R = Intersect(R.EntireColumn, ActiveSheet.UsedRange)
ReDim vRes(1 To R.Rows.Count, 1 To 1)
'Find a "text date" cell to analyze
For Each C In R
With C
If IsDate(.Value) And Not IsNumeric(.Value2) Then
'find delimiter
For i = 1 To Len(.Text)
If Not Mid(.Text, i, 1) Like "#" Then
sDelim = Mid(.Text, i, 1)
Exit For
End If
Next i
'split off any times
V = Split(.Text & " 00:00")
vDateParts = Split(V(0), sDelim)
If vDateParts(0) > 12 Then
FileDateFormat = "DMY"
Exit For
ElseIf vDateParts(1) > 12 Then
FileDateFormat = "MDY"
Exit For
Else
MsgBox "cannot analyze data"
Exit Sub
End If
End If
End With
Next C
If sDelim = "" Then
MsgBox "cannot find problem"
Exit Sub
End If
'Check that analyzed date format different from Windows Regional Settings
Select Case Application.International(xlDateOrder)
Case 0 'MDY
If FileDateFormat = "MDY" Then
MsgBox "File Date Format and Windows Regional Settings match" & vbLf _
& "Look for problem elsewhere"
Exit Sub
End If
Case 1 'DMY
If FileDateFormat = "DMY" Then
MsgBox "File Date Format and Windows Regional Settings match" & vbLf _
& "Look for problem elsewhere"
Exit Sub
End If
End Select
'Process dates
'Could shorten this segment but probably more understandable this way
j = 0
Select Case FileDateFormat
Case "DMY"
For Each C In R
With C
If IsDate(.Value) And IsNumeric(.Value2) Then
'Reverse the day and the month
YR = Year(.Value2)
MN = Day(.Value2)
DY = Month(.Value2)
TM = .Value2 - Int(.Value2)
ElseIf IsDate(.Value) And Not IsNumeric(.Value2) Then
V = Split(.Text & " 00:00") 'remove the time
vDateParts = Split(V(0), sDelim)
YR = vDateParts(2)
MN = vDateParts(1)
DY = vDateParts(0)
TM = TimeValue(V(1))
Else
YR = 0
End If
j = j + 1
If YR = 0 Then
vRes(j, 1) = C.Value
Else
vRes(j, 1) = DateSerial(YR, MN, DY) + TM
End If
End With
Next C
Case "MDY"
For Each C In R
With C
If IsDate(.Value) And IsNumeric(.Value2) Then
'Reverse the day and the month
YR = Year(.Value2)
MN = Day(.Value2)
DY = Month(.Value2)
TM = .Value2 - Int(.Value2)
ElseIf IsDate(.Value) And Not IsNumeric(.Value2) Then
V = Split(.Text & " 00:00") 'remove the time
vDateParts = Split(V(0), sDelim)
YR = vDateParts(2)
MN = vDateParts(0)
DY = vDateParts(1)
TM = TimeValue(V(1))
Else
YR = 0
End If
j = j + 1
If YR = 0 Then
vRes(j, 1) = C.Value
Else
vRes(j, 1) = DateSerial(YR, MN, DY) + TM
End If
End With
Next C
End Select
With R.Offset(0, 1).EntireColumn
Set C = .Find(what:="*", LookIn:=xlFormulas)
If Not C Is Nothing Then .EntireColumn.Insert
End With
R.Offset(0, 1).Value = vRes
End Sub