VBA - How to remove string of characters in a range cell - vba

This is the value of my date Mar 30 2016 4:46:34:256PM i want to remove the Time to make it like this Mar 30 2016.
I've tried various ways to format this if value with the format like mm-dd-yyyy , mm-dd-yyyy , yyyy-mm-dd etc. it's working but if tried this Mar 30 2016 4:46:34:256PM as value it's not working. can someone please tell me why?
I tried a simple code to test all the formats but it's not working with this value Mar 30 2016 4:46:34:256PM so i decided to remove the 4:46:34:256PM and that's how i got stock....
Sub formateDate()
Dim lastrow As Long
lastrow = Sheet1.Cells(Rows.Count, 1).End(xlUp).Row
For i = 2 To lastrow
Cells(i, 2).NumberFormat = ("dd-mm-yyyy")
Next i
End Sub

from your example you seem to have two consecutive spaces after the year number
should it always be so you could go like follows
Cells(i, 2) = Left(Cells(i, 2), InStr(Cells(i, 2), " ") - 1)
and then you can also assign it date formats since IsDate WorksheetFunction returns True if called on the resulting values

Related

VBA: If statement to replace week number with text

In my workbook "isum", I have the week number figured out by a WEEKNUM formula (right now is week 27) listed on column X under the label Week#. The worksheet is called "Orders" with data to see what orders are late. I am struggling to create an if/then statement that makes it so that all of the week numbers on column X (starting at X2) that are < 27 (the current week number out of 52) are labeled as "Late". I am not sure how to change this value to the text, but the hard part is making sure that each week changes until it gets to 52. Otherwise nothing will change that is "Late". If this does not make sense let me know, but this is what I have so far:
isum.Sheets("Orders").Activate
Range("X2").Formula = "=WEEKNUM(RC[-9])"
Range("X2", "X" & Cells(Rows.Count, 1).End(xlUp).Row).FillDown
'Change statement to say "Late" and account for changing week numbers after every week
If cell.Value < 27 Then cell.Value = "Late"
Try looping through the range
Dim col As Range: Set col = Worksheets("Orders").Range("X2:X" & <current week num>)
Dim i As Integer
For i = 1 To col.Rows.Count
col.Cells(RowIndex:=i, ColumnIndex:="X").Value = "Late"
Next
(http://codevba.com/excel/for_each_cell_in_range.htm)
I would suggest a custom number format that displays Late for weeknums less than 27 but retains the underlying numerical weeknum value for use in future calculations. This can be applied through a conditional formatting rule that checks the weeknum formula's result against the current weeknum for dynamic results week to week.
With isum.workSheets("Orders")
With .Range(.Cells(2, "X"), .Cells(.Rows.Count, "O").End(xlUp).Offset(0, 9))
.Formula = "=weeknum(o2)"
.NumberFormat = "0_)"
.FormatConditions.Delete
With .FormatConditions.Add(Type:=xlExpression, Formula1:="=x2<weeknum(today())")
.NumberFormat = "L\at\e_)"
'optionally apply a red fill color
'.interior.color = vbred
End With
End With
End With

"Runtime error 13 - Type mismatch" when parsing date from a text cell

I'm importing a .csv file from another program into Excel. The date format is text, formatted as follows :
mm/dd/yy or
07/03/17
The imported file is very unstructured, with more than just dates in the first field.
I want to write 2017-07-03 into the cell (2,13)
Here is the code I'm using
ActiveSheet.Cells(2, 13).Select
ActiveCell.FormulaR1C1 = "=IF(LEN(RC[-12]))=8, _ 'How I identify date
20&MID((RC[-12]),7,2)&" - "& 'To get 2017 4 digit Year
MID((RC[-12]),1,2)&" - "& 'To extract 2 digit month
MID((RC[-12]),4,2)),"""")" 'To extract 2 digit day
This gives me Runtime error 13 - Type mismatch.
I think that my code is causing the error by mixing values and text, but I cannot see where.
The reasons for your error message is due to the formula not being properly created.
It should look like:
Cells(2, 13).FormulaR1C1 = "=IF(LEN(RC[-12])=8, 20 & MID(RC[-12],7,2) & ""-"" & MID(RC[-12],1,2) & ""-"" & MID(RC[-12],4,2),"""")"
Instead of writing formulas to the worksheet, I suggest doing the conversion within VBA and then writing the results to the worksheet. This can make your code easier to understand, debug, and maintain in the future.
The code below could be shortened, but purposely is not so as to provide more clarity. It is written as a macro that will process everything in column A, and write the dates to column M, in the format you specify.
I note that in your question, you specify a format of 2017-07-03, but in your code, you generate a format of 2017 - 07 - 03. I generated the former in the code, but it should be obvious how to change to the latter if that is what you really want.
Also note that in the code I used the default conversion for Excel for 2-digit years, where two digit years are assumed to be in the range 1930 - 2029. That can be changed if necessary.
The code uses a more involved method of assuring the value being converted is truly a date. But it does not check for "illegal" dates and will convert, for example 2/31/17 to 2017-03-03. Your formula method would return the string 2017-02-31 It would be trivial, in the VBA macro, to add code to flag this kind of problem, if it might be an issue.
There are other ways to check for valid dates, including seeing if CDate or VBA's DateValue functions return a date or an error. But these may not work properly across workbooks in different locale's, with different default short date formats in the windows Regional Settings.
Instead of writing the results as text, the results could be written as a real date formatted as you wish with the .numberformat property of the cell (which could be used in future calculations), and that option is in the comments in the macro.
If you require that the result be dynamic, with a formula, the macro could be easily converted into a User Defined Function, but you would have to assure that the cell format is "text" else Excel will try to convert the resultant date into a "real date" (depending on which of the two formats you really want).
Post back with any questions about the code.
Option Explicit
Sub ConvertOnlyDates()
Dim V As Variant
Dim YR As Long, MN As Long, DY As Long
Dim DT As Date
Dim WS As Worksheet
Dim rSrc As Range, C As Range
'Define the range to check: Columns A
'Always best to explicitly define worksheets and cells
' and not rely on ActiveSheet, Activate, Select, etc
Set WS = Worksheets("sheet2")
With WS
Set rSrc = .Range(.Cells(1, 1), .Cells(.Rows.Count, 1).End(xlUp))
End With
For Each C In rSrc
'check if a date
V = Split(C.Text, "/")
If UBound(V) = 2 Then
If V(0) > 0 And V(0) <= 12 _
And V(1) > 0 And V(1) <= 31 _
And V(2) >= 0 And V(2) <= 99 Then
MN = V(0)
DY = V(1)
'note that this is Excel's default (at least for now)
YR = V(2) + IIf(V(2) < 30, 2000, 1900)
DT = DateSerial(YR, MN, DY)
'Can be written as text
' or as a real date with proper formatting
' REAL DATE
'With C.Offset(0, 12) 'write in column M
' .NumberFormat = "yyyy-mm-dd"
' .Value = DT
'End With
With C.Offset(0, 12)
.NumberFormat = "#"
.Value = Format(DT, "yyyy-mm-dd")
End With
End If
End If
Next C
End Sub
You haven't appropriately closed your strings with double quotes for each line. Using the continuation character _ doesn't allow you to break a string in the middle. You can do this if you properly concatenate:
ActiveCell.FormulaR1C1 = "=IF(LEN(RC[-12]))=8," & _ 'How I identify date
"20&MID((RC[-12]),7,2)&" - " & _ 'To get 2017 4 digit Year
"MID((RC[-12]),1,2)&" - " & _ 'To extract 2 digit month
"MID((RC[-12]),4,2)),"""")" 'To extract 2 digit day
(Your code will be far more readable if you take the time to indent continued lines in the fashion shown above. You can more quickly and easily pick out the destination variable and the assignment if you follow this format.)

Date conversion error in dynamic table value filter

Working with excel-Access VBA environment. The vba code in the excel page assigns the value of a date cell to the date filter. Since I always work dd/mm/yyyy format with panama locale, the code works fine for dates after the 12th (meaning there's no ambiguity to designate the month), but for days les than 13, it converts the day to its numeric value and I get an error message saying 42502 (for may 12,2016 for example) is not a valid value for the filter. When the day passes the 12th, it works fine. How can i trap this error and solve it ?
Code :
ActiveSheet.PivotTables("PivotTable1").PivotCache.Refresh
' Range R1 contains the value we desire to filter the date of dynamic table
' Range B1 contains the date filter of the dynamic table
Range("B1").Select
ActiveSheet.PivotTables("PivotTable1").PivotFields("fecha").ClearAllFilters
Application.ScreenUpdating = False
'ActiveSheet.Range("B1") = Range("R1").Value
ff = Range("R1").Value
ActiveSheet.Range("B1") = Right("00" & Day(ff), 2) & "/" & Right("00" & Month(ff), 2) & "/" & Year(ff)
Application.ScreenUpdating = True
This is one of the many ways Ive tried to solve this, but only works for days after the 12th of the month
It would be helpful if you posted some code, but I believe the problem is you need to specify in code what format you are using instead of letting VBA guess it for you. Since Microsoft is a US company and we use the MM/DD/YYYY format, it could be defaulting to the US format, but then when it reaches the 13th, it defaults to the non-US format by the context of the date.
Try this:
Dim lastRow, i As Long
Dim datStg As String
lastRow = Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
For i = 2 To lastRow
dateStg = Cells(i, "R").Text
If datStg <> "" Then
Cells(i, "B").Value = DateSerial(Mid(dateStg, 8, 4), Mid(dateStg, 5, 2), Mid(dateStg, 2, 2))
Cells(i, "B").NumberFormat = "dd/mm/yyyy"
End If
Next i

Selecting a sheet from the value in a cell

Is it possible to select a sheet based on the value in the cell. For example
Col_1 Col_2 Col_3
gor 100 jan
mack 60 jan
john 40 mar---->this data
..... So on
Here am checking for persons who have below 50 hours and if they have 50 hours then i have to go to that sheet and mark them to represent them.
here john has below 50 hours then i have to get the sheet name from the col_3 that's here March. I have to goto that mar sheet and mark them. My question is that. Is it possible to select or get a sheet name based on the value in a cell.
If your cell value is a date string, you can use Format to put it in the string format you require. For example, if your cell contains "3/15/15", you can turn this into the sheet name "Mar-15" using the code below:
Dim dateVal As String
' assume this is your active sheet
Worksheets(1).Activate
' for simplicity, just set a date
Cells(1, 1).Value = "3/15/15"
' read the date from the cell and format to get month name
dateVal = Format(Cells(1, 1).Value, "mmm-YY")
MsgBox ("Month from Date: " & dateVal)
Output shows:
Note that you may need to adjust for the format of your date, as I'm working with a US-English format, but the concept is to format what the value in the cell contains into what you want.
About this line
ws = Worksheets(Worksheets("Report").Range("H" & intRow1).Value).Activate –
When you want to select or activate any value from particular sheet then those sheet must be activate o/w it gives an error.
Try use the below code. It is written for activecell only but can be extended for range of cell.
Dim sname As String
If ActiveCell.Value < 50 Then
sname = ActiveCell.Offset(0, 1).Value & "-" & "15"
Sheets(sname).Select
End If

cleaning excel sheet with vba

I have an excel sheet with lots of data. As you may know, this comes with lots of problems. One major one is having too much data. I am not familiar with vba, but I wanted to know how to clean data.
I have a sheet with 3 fields: date, time, and temp. The temperature is recorded on a minute by minute basis. The temperature is only recorded from 7 am to 10 pm, but the sheet is on a 24 hour basis. So my sheet has a lot of blank cells. So, I want to write a code that states:
if ((time < 7am) or (time > 10pm)):
delete row
Can I do this?
Also, another problem is that the data is not collected on weekends. I am not given a day field, only a date field in this format: 20130102 which is January 02 2013. I want to:
if ((date = saturday) or (date = sunday)):
delete row
Are either of these doable?
My sheets looks like the following:
A .............. B ......... .... C
date........ time ......... temp
Since both your dates and times are formatted differently than normal, we need to manipulate the values to get something to test against. Consider the following example (I've commented each line to help you follow along):
Sub DeleteRows()
Dim lastRow As Long
Dim Cell As Long
Dim dt As Date
'Work with the active sheet.
With ActiveSheet
'Find the last row of your dataset.
lastRow = .Range("A:A").Find("*", searchdirection:=xlPrevious).Row
'Format your time column to a readable time.
.Columns("B").NumberFormat = "[$-F400]h:mm:ss AM/PM"
'Loop through the rows, beginning at the bottom.
For Cell = lastRow To 2 Step -1
'Piece together the date.
dt = Mid(.Cells(Cell, 1), 7, 2) & "/" & _
Mid(.Cells(Cell, 1), 5, 2) & "/" & Left(.Cells(Cell, 1), 4)
'If the date is a Sat or Sun, delete the row.
If Weekday(dt) = 1 Or Weekday(dt) = 7 Then
.Rows(Cell).EntireRow.Delete
'If the time is before 7am or after 10pm, delete the row.
ElseIf Hour(.Cells(Cell, 1)) < 7 Or Hour(.Cells(Cell, 1)) > 22 Then
.Rows(Cell).EntireRow.Delete
End If
Next Cell
End With
MsgBox "Done!"
End Sub
A few things to note about the code. First, we must start at the bottom of the list because as we delete rows, the remaining rows shift upwards. If we were to go from top to bottom (e.g. A1 to A10), if we deleted row 5, row 6 would slide into its place, and the loop would skip row 5 (previously row 6) and go on to row 6. In other words, looping from top to bottom when deleting rows will ultimately skip rows unintentionally.
Second, I had to guess on your time format. While I believe I guessed correctly, I may not have. If I was wrong and my code doesn't change the time column into a readable time, record a macro while changing the format of that column and substitute the new format with mine ("[$-F400]h:mm:ss AM/PM"
).
And lastly, since your date column is an abnormal format (for Excel), we need to reorder the date so that Excel can read it. Once we've done that, we can use the resulting date to see if the date was a Sat. or Sun.
You can do it this way, assuming the column that contains your date is the 2nd (B) :
Dim i As Integer
for i = 1 to cellsCount
If Hour(Cells(i, 2)) < 7 Or Hour(Cells(i, 2) > 22 Then
Rows(i).Delete
Else If WeekDay(Cells(i, 2)) = 7 Or WeekDay(Cells(i, 2)) = 1 Then
Rows(i).Delete
End If
next
You can have more information about the WeekDay function here :
http://msdn.microsoft.com/en-us/library/82yfs2zh%28v=vs.90%29.aspx