How to convert multiple column from text to date? - vba

In my excel file, there are hundred columns. I want to convert some columns (eg. Column A, C,F, G..) from text to date. It really take time if manually change each column one column by one.
How can I do it ? By using VBA ?
The original text column format just like '31-Dec-2011 00:00:00'. I want to convert to 'dd/mm/yyyy' 31/12/2011
Thanks

If you actually want to chop the time off in each of the cells then this might be an approach:
If the target times are in column A of a sheet called "target" and the column header in A1 is "StartTime"
You could amend the below and add an argument so that it takes the column address. Then it could be called several times to carry out this operation on several columns.
Sub ChopOffTime()
dim mySheetName as string
mysheetname = "target" '<<<<change to your sheet name
myLstRow = Excel.ActiveWorkbook.Sheets(mysheetname ).Cells(Excel.ActiveWorkbook.Sheets(mysheetname ).Rows.Count, Excel.ActiveWorkbook.Sheets(mysheetname).Range("A2").Column).End(Excel.xlUp).Row
With Excel.ActiveWorkbook.Sheets(mysheetname)
.Columns("B:B").Insert Excel.xlToRight
.Range("B2:B" & myLstRow).FormulaR1C1 = "=TIME(HOUR(RC[-1]),MINUTE(RC[-1]), SECOND(RC[-1]))"
.Range("B1") = "StartTime" '<<<<<change to appropriate header
.Columns("B:B").Copy
.Columns("A:A").PasteSpecial Excel.xlPasteValues
.Columns("B:B").Delete Excel.xlToLeft
End With
End Sub

Thanks all.
To simplified the procedure, I just developed some macro for user to run to change the column format, and then they can import the excel the mdb without error.

Use the following for the columns in question:
Columns("A:A").Select
Selection.NumberFormat = "m/d/yyyy"

Related

How to copy/paste formula in filtered/visible cells via VBA in Excel

I am struggling with copying and pasting formula from one column to another one within using filter in another column.
I got a table with 52 columns (number of rows is changing each month).
In column AW (#49) I have applied filter. It shows only CTD.
After applying this filter I need to copy formula from column AH to column AG. Of course I need to apply this only for filtered/visible cells.
The code I have written is copying/pasting this formula into all cells in column AG (it doesn't consider my filter in column AW).
Another problem is that when applying the filter in column AW then the first visible row doesn't need to be all the time AH2 but it can be e.g. AH15 or whatever. I guess this could be avoid via some dynamic solution. Unfortunately I have no clue how to do it.
Afterwards I would like to apply the same for filters in another columns.
Many warm thanks in advance for any hint! :)
This is my code:
Sub ApplyFilterInColumnAW()
Sheets("DATA").Select
ActiveSheet.ListObjects("tb_DATA").Range.AutoFilter Field:=49, Criteria1:="CTD"
Range("AG2").Select 'dynamic solution?
ActiveCell.FormulaR1C1 = "=[#[Service/Log Formula]]" 'header name of column AH
End Sub
Range.Copy and Range.Paste only work on visible cells. In my example I target the cells in the column using the Column Header.
Sub ApplyFilterInColumnAW()
Const TagetColumnLabel = "Test"
Dim tbl As ListObject
Set tbl = Sheets("DATA").ListObjects("tb_DATA")
With Sheets("DATA")
.ListObjects("tb_DATA").Range.AutoFilter Field:=49, Criteria1:="CTD"
tbl.ListColumns(TagetColumnLabel).DataBodyRange.FormulaR1C1 = "=tb_DATA[[#This Row],[Service/Log Formula]]"
End With
End Sub

excel macro to change values in a column

I have a file coming every month which has few columns with more than 50K rows. I usually need to replace values in column B with different values such as if any field in column B contains ASD , replace it with XYZ. And there is a list of value that needs to be replaced. Also as mentioned above old value can be more than once in column B and needs to be replaced .
Any help would be great.
Thanks
Record a macro [View > Macros > Record Macro]
Do the find+replace operation
Stop recording.
Now view Macros > Edit.
You will see the newly recorded Macro which does the find+replace, and you can edit this to your exact requirements.
Try that:
Sub test()
'this will get you the last row number in column "B"
lastRow = Sheets("SheetName").Cells(Sheets("SheetName").Rows.Count,"B").End(xlUp).Row
'loop through all cells in coulmn "B" and replace text as needed
For i = 1 To lastRow
'you can add multiple lines for each values that needs to be replaced
Sheets("SheetName").Cells(i, 2).Value = Replace(Sheets("SheetName").Cells(i, 2).Value, "ABC", "XYX")
Next i
End Sub
Where 'SheetName' is your sheet's name. Hope that is what you are looking for!

Excel VBA: Copy the Data up to the last column that has value

The spreadsheet has multiple values in a cell.
What I'm trying to do is get that value found in a cell and paste it to another sheet and copy the other fields(columns) that belong to that value. How do I set the range in order copy the other fields(columns) up to the last column that has value? Thanks in advance.
For iRowGetProdCode = 0 To UBound(sSplitProdCode)
Sheets("Output").Cells(iRowCountOutput, 1).Value = sSplitProdCode(iRowGetProdCode)
iRowCountOutput = iRowCountOutput + 1
Next iRowGetProdCode
here is an idea how to discover an un-empty columns in the same row,
maybe you will find it useful and manipulate it for your needs:
Function LoopUntilLastColumn(ByVal Row As Integer)
Dim i As Integer
i = 1
Do While Cells(Row, i) <> ""
' do somthing
MsgBox (" I AM ALIVE COLUMN!")
i = i + 1
Loop
' you can also use the return value of the function.
LoopUntilLastColumn = i
End Function
I'm not exactly sure about what you're asking, but here are my three best guesses.
1.) Splitting delimited data from a single cell to columns
Without VBA: Use the "Text to Columns" function (Excel Ribbon:
Data|Data Tools).
With VBA: Use the split function MSDN (Related Post), then assign array values to target cells. Or parse your string manually with a loop.
2.) Finding the end of a continuous range
Without VBA: Use ctrl + arrow key
With VBA: Use the Range.End Property
3.) Looping through columns and rows
Used a nested loop:
For c = 1 to 5
For r = 1 to 20
Cells(r,c) = "Row = " & r & ", Column = " & C
Next
Next
Editing Suggestions (I don't have enough reputation to directly comment or edit)
This question as worded may be too specific for StackOverflow. Consider re-wording so that the problem can be understood in a general context and your question can be more useful to others.
Also, the wording is a little confusing. For example, use of the term "value" seems to change from referring to delimited data to referring to cell content in VBA. Likewise, it can be confusing to use "fields" or "columns" to describe the data if it's actually delimited text, so clarity on the data's state of existence would help.
It also seems to me that you've parsed the string on it's delimiter to an array, and that you're looping through this array to write the data in rows. I still can't see how exactly your question about setting a range fits in.

Sorting Worksheet data by column values using Excel VBA

I have next userform developed in vba, which takes info from a worksheet for displaying info
I want to order all the info aphabetically by a Segment, this is the code:
Function llenarDatosTabla()
Dim vList As Variant
Dim ws As Worksheet: Set ws = Worksheets(BD_PRODXSIST)
ListBox1.Clear
With ws
If (IsEmpty(.Range("AA2").Value) = False) Then
Dim ultimoRenglon As Long: ultimoRenglon = devolverUltimoRenglonDeColumna("A1", BD_PRODXSIST)
vList = ws.Range("AA2:AA" & ultimoRenglon & ":AL2").Value
If IsArray(vList) Then
Me.ListBox1.List = vList
Else
Me.ListBox1.AddItem (vList)
End If
End If
Me.ListBox1.ListIndex = -1
End With
Set vList = Nothing
Set ws = Nothing
End Function
how to make it ordered by 'AD' (SEGMENTO) column???
You can sort your Excel Worksheet in ascending order using VBA statement like the following:
Columns("A:XFD").Sort key1:=Range("AD:AD"), order1:=xlAscending, Header:=xlYes
Note: in the column range Columns("A:XFD") instead of XFD enter the last used column pertinent to your case, e.g. Columns("A:DD").
Hope this will help.
To sort a data table, use Excel Names in conjunction with the CurrentRegion function. This is less risky than hard-coding column references and can be done in two simple steps.
The reason it's preferable to specifying columns is that if you get the columns wrong or they change later, you'll scramble your data! When you perform the sort, the cells in any omitted column(s) will remain where they are, becoming part of the wrong rows. And this is exactly what will happen if you add further columns later, unless you remember to update your VBA.
Here are the two simple steps for using this approach. For this example, I've chosen a data table with four columns and four rows:
We are going to sort by COL3 descending. The cells in the other three columns share identical values, enabling us to readily verify they all stay with the correct rows.
Step 1: choose a cell in the data table that's unlikely to ever be removed, such as the header of a column you intend to make permanent, and define a Name for this cell. You can define the name by selecting the cell and typing directly in Excel's Name dropdown above the worksheet. Here I've used the name RegionTag:
Straight away, CurrentRegion can reference the whole data table just from this. You can see it in action if you code a line of VBA to select the table:
Range("RegionTag").CurrentRegion.Select
This is the result:
That's just for illustration, showing the power of the Name/CurrentRegion combination. We don't need to select the table in order to sort it.
Step 2: define a second Name, this time for the column you want to sort by:
Make sure the Name refers to the entire column, selected by clicking the column header, rather than just a range of cells in the column.
That's it! With these two Names defined, we can sort the data table without concerning ourselves with its rows and columns, even if more are added later:
Range("RegionTag").CurrentRegion.Sort _
key1:=Range("SortCol"), order1:=xlDescending, Header:=xlYes
Here is our data table sorted using the above statement:

SUMIFS formula to fill data in cell depends upon date and name and also keep previous data in a cell

I have an excel with two sheets named raw and data here
raw sheet :
date sheet :
In raw sheet I will be uploading data manually.
What I am looking for :
In this, I want to create a formula which will check each name from the data sheet in raw sheet and it has to pick the total value (D column in raw) and update the same in data sheet in a cell which matches with last modified date.
For example :
Name is R420864561 and its last modified date is 20141201 and total value is 10.
So in my data sheet, it has to be updated like this
Above, value 10 is updated in a cell which matches the last modified from raw sheet with date in data sheet, here both are 20141201.
I am using below formula for this (formula in C3)
=SUMIFS(raw!$D:$D,raw!$A:$A,$A3,raw!$C:$C,C$2)
Now, if last modified date 20141202 with total 50
Now, data sheet will updated like below using above formula
What I need now :
In above, if I update value in another date, the data updated in previous date is getting changing to 0. But I need to keep that data in that cell, if there is no update in that.
In above case, I need to keep previous data (for date 2014201)10 in data sheet cell C3, and update 50 in D3 (for date 20141202)
I have added below code with macro, to copy paste the formula value, as simple value
Dim rngCell As Range
For Each rngCell In ActiveWindow.RangeSelection
rngCell.Value = rngCell.Value
Next rngCell
But that is not working here, It still resetting previous value to 0 when I update for a different date.
Any suggestion to correct this is much appreciated
I have uploaded the copy of the excel which I am working in below location :
https://www.dropbox.com/s/jpubzqbco5mflu5/1.1_test.xlsm?dl=0
This should work assuming your loop is correct.
rngCell.Copy
rngCell.PasteSpecial Paste:=xlPasteValues
Try For Each rngCell In Application.Selection to start the loop
you VBA is wrong:
update it using this one:
Sub saveMyData()
Set ws = ActiveSheet
ws.Range("C3:E999").Copy
ws.Range("C3").PasteSpecial Paste:=xlPasteValues
Application.CutCopyMode = False
Range("C3").Formula = "=SUMIFS(raw!$D:$D,raw!$A:$A,$A3,raw!$C:$C,C$2)"
Range("D3").Formula = "=SUMIFS(raw!$D:$D,raw!$A:$A,$A3,raw!$C:$C,D$2)"
Range("E3").Formula = "=SUMIFS(raw!$D:$D,raw!$A:$A,$A3,raw!$C:$C,E$2)"
End Sub
Here is ***UPDATED***the example sheet to try and see if it works.
it was because your VBA code was mixed up with unncessary codes.
From all appearances, the problem is with how you are presenting the question and plan to use the raw spreadsheet. From the information provided, it seems like you plan on entering records in raw, but then you also intend to change them. Also, based on your example and how you are describing the problem, it's not clear why you are using SUMIFS rather than INDEX(MATCH).
It would seem that your raw spreadsheet should have multiple records, one for each Name/Last Modified combination, and more than one for each combination to necessitate the use of SUMIFS. Then your formula in data will pick up the relevant info in raw.
If you plan on only having one entry for each Name in raw, and changing the last modified date and the total in raw it seems rather pointless to have separate spreadsheets at all, just enter it into data in the first place under the respective last modified date.