Converting a static formula to selection code VBA macro - excel

I'm working on an record processing tool and have run into a problem.
One of our clients provides us with raw data that contains carriage breaks - making it unusable until formatted. Unfortunately the easy solution of running a clean function can't be used as it erases the last digit of the 16-digit account numbers in the process. Hoping that every end user remembers to keep destination formatting when porting the data over to have it formatted into text strings isn't really an option either.
So here's my plea for help:
I was able to get a clean value by using this formula
=IF(RIGHT(A2,1)=" ",LEFT(A2,LEN(A2)-1),A2)
I now need to turn it into a macro that will change the cell.value of the selected cells to the result of the formula. But after 8 hours of banging my head against the wall I just can't figure out how to do it. Any help is much appreciated!

Your formula in VBA:
Sub Klean()
Dim Cell As Range
For Each Cell In Selection
v = Cell.Value
If Right(v, 1) = " " Then
v = Left(v, Len(v) - 1)
Cell.Value = v
End If
Next Cell
End Sub

You need a function that iterates over a given set of cells. You can call that function using whatever cells are currently selected.
Option Explicit
Sub DoSomethingCool()
CleanCellText Selection
'--- or ---
CleanCellText ActiveSheet.Range("A1:Z20")
End Sub
Public Sub CleanCellText(ByRef thisRange As Range)
Dim cell As Range
For Each cell In thisRange
If Right$(cell.Value, 1) = " " Then
cell.Value = Left$(cell.Value, Len(cell.Value) - 1)
End If
Next cell
End Sub

Many thanks to everyone for such quick and informative responses!
I have managed to identify the issue - turns out as well as a carriage break the raw data also contained a tab space in front of the data that twas causing all the issues and was refusing to be edited by trim or manual edit! Here's the final code fr the macro button I embedded that solved the issue:
Private Sub CommandButton6_Click()
Dim Rng As Range
Set Rng = Selection
For Each cell In Rng
If IsEmpty(cell.Value) = False Then
cell.Value = Replace(cell.Value, Chr(9), "'")
End If
Next cell
End Sub
I've set the tab space to be replace by an apostrophe so that final value does not end up getting truncated, like what was happening when i used the clean function.
Once again many thanks everyone!

Related

Trying to run different macros based on value of cell in a range

I am trying to write code that looks at a value, and based on the value ("OPGW" or "Conductor") runs either the OPGW macro or the Conductor macro in another cell further to the right. Then I want it to move down to the next line and do it all again.
So if Cell B8 is OPGW, I want Cell BG8 to run the OPGW code, and then if cell B9 is Conductor, I want cell BG9 to run the Conductor code. There's no problem with the individual macros, though it should be noted that each macro is an exceedingly long formula that SHOULD only take place in the active cell. The only problem I'm having is that it won't go down to the next row and do it all again.
Sub WireUpdate()
N = Cells(Rows.Count, "A").End(xlUp).Row
CR = ActiveCell.Row()
With Range("BG8:BG" & N)
If ActiveSheet.Cells(CR, 2) = "OPGW" Then
Call OPGW2
Else: Call Conductor2
End If
End With
Thank you so much for your help.
I have tried the following code
With Range("BG8:BG" & N)
If ActiveSheet.Cells(CR, 2) = "OPGW" Then
Call OPGW2
Else
If ActiveSheet.Cells(CR, 2) = "Conductor" Then
Call Conductor2
Else: ActiveSheet.Cells(CR, 2) = "0"
End If
End If
End With
I have also tried to make the OPGW and Conductor macros loop, which works, but tends to overwrite the other data. So, it will put in all the OPGW things in, then go through and put all the Conductor things in, overwriting the OPGW things with 0.
I also checked out the following article: Running Different Macros Based on Values in Range but it didn't seem to be what I need, unless it can be adapted in a way I haven't fathomed yet.
This shows one way to loop over a range, and how to call another method based on each cell's value.
Note you need to give the other subs something to work with - you can pass a cell in directly, rather than relying on something like ActiveCell
Sub WireUpdate()
Dim ws As Worksheet, c As Range, n As Long
n = ws.Cells(Rows.Count, "A").End(xlUp).Row
For Each c In ws.Range("BG8:BG" & n).Cells
Select Case c.Value
Case "OPGW": OPGW c '<< call method and pass in the cell
Case Else: Conductor2 c
End Select
Next c
End Sub
Sub OPGW(c As Range)
'do something with c
End Sub
Sub Conductor2(c As Range)
'do something with c
End Sub

How can I execute formular which I insert by VBA?

I wrote some code and have a question.
I sucessfully make macro which insert formular into cell.
Problem is It is not working automatically.
Function test(PCell As Range) As String
test = Chr(61) & Replace(PCell.Address, "$", "")
End Function
Cell shows =N3 (simple example). And I can execute Push "F2" - "Enter". It is working well.
Problem is .. There are more than 100 cells. If there is no solution, I have to push F2 - Enter 100 hundred times.
After select the cells, How can I execute the formular in cells? or by using VBA?
I tried to use Selection.Evaluate() But there is nothing happened. And "F9" key is also.
There is a faster and simpler way to achive this result.
'''vba
Sub ExecuteBulkFormula(SrcRng as Range,TgtRng as Range)
'What this procedure does is it loops through every area in the
'SrcRng and then loops through every cell in this area
'It then writes the formula in the array
'i: Loop Counter
'arr_index: Array Items Counter
'r_area: Every range contains atleast one Area as a Range Object
'The usage of Area is essential, as sometimes if we select multiple
'areas, For Example: A1:C2 & A5:C6, Then we can access these two "areas"
'The screenshot for the areas is added below (Figure 1).
'If however, we don't use Areas then we can only access the first Area
'i.e. A1:C2
Dim i as Long, arr_index as long
Dim r_area as Range
Dim arr as Variant
Redim arr(1 To 1000)
arr_index = 1
For Each r_area In SrcRng.Areas
For i = 1 to r_area.count
'Just Replace the below line to change the formula to fit your needs
arr(arr_index) = Chr(61) & Replace(r_area(i).Address, "$", "")
arr_index = arr_index+1
Next i
Next
Redim Preserve arr(1 To arr_index)
TgtRng.Formula = arr
End Sub
Figure 1
How to use this function?
In excel worksheet, press Alt+F11 or Developer Tab->Visual Basic
Right Click in any item in Project Explorer and then select Insert->Module
In this module, insert this above code.
To run this code you can use the immediate window (Ctrl+G) or write another procedure to run this code.
Suggestions
Instead of using Replace you can use Range.AddressLocal(False,False)
It will produce the same result.
This function ExecuteBulkFormula will run very fast
For 1000 rows: 0.016 sec (or 16 milliseconds)
For Reference my laptop is dual core i7-5500u which is low end.
to have function calculate at every sheet change, just add Application.Volatile (see:https://learn.microsoft.com/en-us/office/vba/api/excel.application.volatile)
Function test(PCell As Range) As String
Application.volatile
test = Chr(61) & Replace(PCell.Address, "$", "")
End Function
to place that cell in all cells of a given range:
Sub PlaceTest()
With Range("A1:A10") ' change the range address to to fit your needs
.Formula = "=test(RC[1])" ' this will feed the function with the cell 1 column to the right of where the function is placed: just play around with R1C1 notation (https://excelchamps.com/formulas/r1c1/)
End With
End Sub

Identify second line of text in a cell with VBA

I have a bunch of cells that have two lines of text in each cell after pulling the data into Excel.
What I am looking to do is use a macro with the Trim function to remove everything in the cell after the second line.
I'm puzzled with this data, it's as if you were to enter data in a cell and Enter down to the next cell, but it's one cell and is not merged.
ex.
Someone's Name [123]
Procedure room, procedure done
Is there a way to identify this line break?
thanks so much for any assistance, my heads spinning and I'm punching out for the day.
cheers
Just look for the ASCII-10. Select the cells you wish to process and run:
Sub KleanUp()
Dim r As Range
For Each r In Selection
r.Value = Split(r.Value, Chr(10))(0)
Next r
End Sub
Only the first line will be retained in each cell.
EDIT#1:
As Ralph points out, ASCII-13 should also be considered, therefore:
Sub KleanUp2()
Dim r As Range
For Each r In Selection
r.Value = Split(Replace(r.Value, Chr(13), Chr(10)), Chr(10))(0)
Next r
End Sub
This converts to a single-style line-break.
EDIT#2:
It is possible to improve the performance of the sub by:
reading the data into a VBA array as a single large block
looping through the array (in VBA)
transferring the data back to the worksheet in a single block

Excel VBA - Convert string entered in user form to number

I have an excel user form into which the user enters numbers, when those numbers are entered into the spreadsheet they appear with the notification that this is a number stored as text. =SUM(H6:H13) shows a zero result.
I have tried NumCrtn = cLng(NumCrtn) - doesn't change the cell to a number, formula still shows zero.
I have tried NumCrtn = Val(NumCrtn) - doesn't change the cell to a number, formula still shows zero.
I have tried copy and paste.special to a value and that doesn't change it to a number either.
Don't know what to do.
Help!
Try this one:
With Range("H6:H13")
.NumberFormat = "0"
.Value = .Value
End With
Edit:
Another solution. Building on Pradeep Kumar's suggestion which deals with preparing your range before you enter the data, Change your code to something like this
Private Sub UserForm_Initialize()
Dim aCell As Range
Range("H6:H13").NumberFormat = "0"
'This is to cater for any previous values if filled in
For Each aCell In Range("H6:H13")
aCell.Formula = aCell.Value
Next
End Sub
Private Sub CommandButton1_Click()
'Entering value for H6
Range("H6").Value = TextBox1.Value
End Sub
Range("H6:H13").NumberFormat = "#,##0"
It is not a VBA solution, but an ordinary Excel solution.
Do like this
Select the column
Select Data - Text to columns
Quite often the default settings will do and you can click Finish. Otherwise you
will have to make sure that the result is just a "General" column
A macro doing just this would look something like this:
Columns("A:A").TextToColumns
There's a lot of parameters to the TextToColumns method, but it should work fine with default values only (i.e. no parameters).

Use current cell value to calculate and replace in cell

I'm very new to VBA in excel and I've tried searching for my question already.
I'm trying to calculate an answer based off the value of the cell and have the calculated value replace the current value upon macro execution. For example if A2 has an initial value of 30 I'd like too replace A2 with =A2*3 so that A2 would read 90 as its new value.
Is there any way to do this without having to copy and paste everything somewhere else first?
Thanks for any help.
Try something like this. First, make sure you have selected at least one cell, and then run the macro from the macros menu:
Sub MultiplyBy30()
Dim rng as Range
Dim cl as Range
Set rng = Range(Selection.Address)
For each cl in rng.Cells
If IsNumeric(cl.Value) And Len(cl.Value) > 0 Then
cl.Formula = "=" & cl.Value & "*30"
End If
Next
End Sub

Resources