Apply formatting to an Excel file programmatically - vba

I want to format an existing Excel file (xls) cell in such a way that the cell values in a column only show two digits after the decimal.
So instead of 0.090919729581319146%, I want to show 0.09%.
I need to do this across multiple documents, so I need some repeatable way to apply the transformation. I was thinking of a macro - and tried it with the integrated macro recorder in Excel 2010, but unfortunately couldn't get it to work.
I have only to format a Range from C3 --> C5000.

I found something on web. Look at this code. It does what i am talking about:
Sub NurZumUeben()
With Range("C2:C5000")
.Replace What:="%", Replacement:="", LookAt:=xlPart, SearchOrder:=xlByRows
Range ("K1") = 100
Range ("K1").Copy
.PasteSpecial Paste :=xlPasteAll, Operation:= xlDivide
.NumberFormat = "0.00%"
Range("K1").Clear
End With
End Sub

Related

Directly converting a range of numeral entries to text with VBA

I have a huge list, which I have to work on each day. I want to change my reference columns data from number to text so it enables me to do some advanced filtering and referencing futures. I don't want to add any new column and for instance, use Text() function in excel as this range is same in different files I have to concatenate and link. I am just wondering if it is possible to do that in place with a VBA code or not. I tried:
selection=selection.text
or doing some paste special efforts with ', empty cells and converting to array back and forth but not succeded. Any idea? I also don't want to do a loop as I need to this effort for several files which I can't manipulate their structure or change them with my weak laptop each time every day!
Regards,
M
You may want to use built-in Excel functionality Text-to-columns.
If you want it automated using VBA, try this:
With Sheet1
.Range("B1", "B4").TextToColumns Destination:=.Range("B1"), _
DataType:=xlDelimited, _
FieldInfo:=Array(1, 2)
End With
Above converts all numbers in the range B1:B4 in sheet1.
The FieldInfo argument identifies the conversion.
We use Array(1,2) which means we want to convert column 1 to text.
Check Text to columns functionality to understand it further. HTH.
This should help you out. It converts a a range of values into text format
Sub Convert_To_Text()
Dim vData As Variant
vData = Range("A1:D1")
Range("A1:D1").NumberFormat = "#"
Range("A1:D1") = vData
End Sub
Based on #l42 answer and point here is what I was needed... and came to
Sub NumbtoText()
If Not ActiveSheet.FilterMode Then Selection.TextToColumns _
DataType:=xlDelimited, _
FieldInfo:=Array(1, 2)
End Sub
Thanks

Making an excel VBA macro to change dates and format

I'm a complete novice at macros but I've had trouble finding the exact solutions I need, and more trouble combining them. I get this raw data report which needs a couple of changes before I can input it into our master data set for reporting. These things need to happen (please refer to the picture):
The date needs to be expressed in the formation "mmm-yy". I've tried to add "01/" to make "01/04/2017" (I'm Australian so this is the 1st of April), but for some reason it automatically changes it to 04/01/2017. Ultimately, I need 04/2017 to go to Apr-17 for all data in the column
"Medical Div" change to "Medical" and "Mental Health Div" change to "Mental Health" - i've already sorted a macro for this, but not sure how to combine it with another macro for the other functions I'm wanting.
If anyone can help providing code or links to good resources which will allow me to perform all these functions at once with one macro that would be great.
Thanks
This can easily be done with Power Query instead of VBA. Power Query is a free add-in from Microsoft for Excel 2010 and 2013 and built into Excel 2016 as "Get and Transform". Conceptually, the steps are:
Load the data
insert a new column with a formula that combines the text "1/" with the column Month-Year
change the type of the new column to Date
remove the old Month-Year column
select the Division column
replace " Div" with nothing
Save the query
When new data gets added to the original data source, just refresh the query. All this can be achieved by clicking icons and buttons in the user interface. No coding required.
Well, for point 2, how about recording a macro and using Find and Replace twice?
This should combine them into a macro for you. Then you can copy paste that elsewhere.
As for the date, Excel has an predisposition to convert to US format. Try this first (assuming "Month-Year" column is B)
Range("B2") = DateValue(Range("B2"))
Then apply formatting later.
Private Sub mySub()
Dim myRng As Range
Dim r As Range
Dim LastRow As Long
Dim mySheet As Worksheet
Dim myFind1, myFind2 As Variant
Dim myReplace1, myReplace2 As Variant
'This will get the number of rows with value in the sheet
LastRow = Sheets("Sheet1").UsedRange.Rows.Count
'This is for the first find and replace. It will search all cells with exact value of "Medical Div" in the sheet and change it to "Medical".
myFind1 = "Medical Div"
myReplace1 = "Medical"
'This is for the second find and replace. It will search all cells with exact value of "Mental Health Div" in the sheet and change it to "Mental Health".
myFind2 = "Mental Health Div"
myReplace2 = "Mental Health"
'This will loop through the entire column with the date that needs to have the format mmm-yy. It will convert the 04/2017 to date format first before making it Apr-17.
With Sheets("Sheet1")
Set myRng = Sheets("Sheet1").Range("A2:A" & LastRow)
For Each r In myRng
r.Value = CDate(r.Value)
Next r
End With
myRng.NumberFormat = "mmm-yy"
'This will loop through the active worksheet and apply the find and replace declared above.
For Each mySheet In ActiveWorkbook.Worksheets
mySheet.Cells.Replace what:=myFind1, Replacement:=myReplace1, _
LookAt:=xlWhole, SearchOrder:=xlByRows, MatchCase:=False, _
SearchFormat:=False, ReplaceFormat:=False
mySheet.Cells.Replace what:=myFind2, Replacement:=myReplace2, _
LookAt:=xlWhole, SearchOrder:=xlByRows, MatchCase:=False, _
SearchFormat:=False, ReplaceFormat:=False
Next mySheet
End Sub
Here is a code that you could try.
It will change the date format of the column with Month-Year to
"Apr-17" regardless of the current date format.
It will also find and replace the Medical Div and Mental Health Div
to "Medical" and "Mental Health".
You will need to change the range to suit your needs. I have set the column for the month-year to column A. You must change it to column B if that is where your dates are.
This is my data before running the macro:
Here is my data after running the macro:

Find a cell with Today's date in C4:V4 and paste content into cells below

I'm trying to figure out how to write a code that would :
copy contents of Array A,
look into Array B at the headers with dates,
find current date
and paste the contents directly beneath that cell.
So far the best I managed to achieve was have a macro find the date if I typed today's date specifically.
Edit: I was trying to repurpose a record macro and while the first time I recorded the same macro it worked, the next times it didn't all of sudden.
Sub Macro1()
Dim myDate As String
myDate = Format(Date, DDMMYYY)
Range("A5:A11").Select
Selection.Copy
Range("Table29[[#Headers],[23/01/2017]:[11/02/2017]]").Select
Selection.Find(What:="25/01/2017", After:=ActiveCell, LookIn:=xlFormulas _
, LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False).Activate
Range(ActiveCell.Offset(1, 0), ActiveCell.Offset(7, 0)).Select
ActiveSheet.Paste
End Sub
Also I'm not sure but I feel like I was lacking some reference to activate Date function in VBA because whenever I try to use it I keep getting errors, even when I try to replicate other codes I found on google with Date in them.
Edit 2: I managed to get as far as paste stuff into desired array, but I still struggle to make Date work. If I don't manually type in the date, it won't work.

VBA AutoFilter hiding all rows - including the ones matching criteria

I'm applying VBA AutoFilter to some results in an excel sheet. It seems to compile properly, but when I check the results, the AutoFilter is hiding both the rows that match and that do not match the criteria I applied.
If I manually select the autofilter that was applied, i see that the criteria that I coded is correctly input and, by just clicking enter, the criteria matching rows show.
I'm using a Brazilian Portuguese version of Excel, not sure if that might be the issue.
Here's what I've tried:
Sub FilterOff(ByVal thisSheet)
thisSheet.Activate
With thisSheet
.AutoFilterMode = False
.Range("A1:F1").AutoFilter
.Range("A1:F1").AutoFilter Field:=4, Criteria1:=">0.01", _
Operator:=xlOr, Criteria2:="<-0.01"
.Range("A1:F1").AutoFilter Field:=5, Criteria1:=">100"
End With
End Sub
I was experiencing something similar in one of my macros. I had a table that I was trying to autofilter. I could do it manually, but not in VBA, even when I was exactly replicating what the recording function gave me. I also could not copy+paste as values in VBA, but I could manually.
What worked for me was to save and close the workbook, then reopen it and apply the autofilter. Specifically, I used this:
tempWb.SaveAs ("dir\temp.xlsx")
tempWb.Close (0)
Set rptWb = Workbooks.Open("dir\temp.xlsx")
Set rptWs = rptWb.Sheets(1)
rptWs.Range(rptWs.Cells(1, 1), rptWs.Cells(lstRow, lstCol)).AutoFilter Field:=20, Criteria1:="=NO RECORD"
and it worked.
Update: I think the underlying issue was that I had calculation set to manual. After I set calculation to automatic, the problems went away.
I did something like this and it worked
Range("A1:B6").AutoFilter
ActiveSheet.Range("$A$1:$B$6").AutoFilter Field:=1, Criteria1:="=10", _
Operator:=xlOr, Criteria2:="=30"
ActiveSheet.Range("$A$1:$B$6").AutoFilter Field:=2, Criteria1:="100"

Excel VBA - transpose formulas in vertical array to horizontal array

I have googled all sorts of phrases for an answer to my question but I'm having a hard time locating a solution that works. It likely involves combination of a few different solutions, or a method I have yet to think of; so any help would be appreciated.
Say I have formulas in cells A1, A2, A3, and A4. Let's say I want those EXACT formulas moved to the right one column.
In VBA I can say:
Range("B1:B4").Formula = Range("A1:A4").Formula
What I'm looking to do is something like this:
Range("B1:E1").Formula = Range("A1:A4").Formula
See how my B:E range is horizontal verses the vertical range of A1:A4.
I have tried all sorts of transpose options but I can't find any that work because I want the EXACT formula's to transfer.
Any thoughts?
You could try something like:
Sub PivotRangeFormulas()
Dim rngSrc As Range: Set rngSrc = ActiveSheet.Range("A1:A4")
Dim rngTgt As Range: Set rngTgt = ActiveSheet.Range("B1:E1")
Dim i As Long: For i = 1 To rngSrc.Rows.Count
Application.Index(rngTgt, i).Formula = Application.Index(rngSrc, i).Formula
Next i
End Sub
You could also use an Offset function from the first cell in each range
Range("B1:E1").Formula = WorksheetFunction.Transpose(Range("A1:A4").Formula)
Is locking the cell reference inside your formulas possible? I'm sure you are aware, but the F4 key (pc) will toggle referenced cell locks. The dollar sign locks the column letter or row number [A6, $A$6, A$6, $A6]. If you lock your cell references, you can then copy and transpose the formulas.
Range("B1:E1").Copy
Range("A1").Select
Selection.PasteSpecial Paste:=xlPasteAll, Operation:=xlNone, SkipBlanks:= _
False, Transpose:=True
Here is another option: Try recording a macro while entering your formula in the cell. If your formula is:
=SUM(D3:D4)
Depending on where you entered the formula, the VBA output might look like:
"=SUM(R[3]C:R[4]C)"
Here is the absolute reference in VBA:
"=SUM(R3C4:R4C4)"
You could then do something like:
Range("A8:A23").FormulaR1C1 = "=SUM(R3C4:R4C4)"
This will enter the formula =SUM($D$3:$D$4) in all the cells from "A8:A23". If you play with the brackets in the VBA formula, you should be able to make it work. The formula below searches the column to the left of the selected cell(s) containing the formula for the text "nff":
Selection.FormulaR1C1 = _
"=SEARCH(""nff"",RC[-1])"