how to use the following excel vba code? - excel

Sub MergeRanges()
Dim rng As Range, txt As String
For Each rng In Selection
txt = txt & rng.Value2
Next
Application.DisplayAlerts = False
Selection.Merge
Selection = txt
Application.DisplayAlerts = True
End Sub
when merge cells, i want to remain all the data in the cells. i googled some time,finding the above code. but i don't know how to use it? and what's the meaning of them. thank you.

Setup:
Open VBA editor (Tools > Macro > Visual Basic Editor) (shortcut Alt-F11)
Insert > Module
Paste the code into your new module.
Use:
Select the cells you want to merge.
Tools > Macro > Macros... (shortcut Alt-F8) > select MergeRanges > Run
If you want the macro to work with "special formats" such as dates, then you should change .Value2 to .Text.

in Excel, press Alt-F8
use the dialog to add an empty macro "MergeRanges"
add your code above.
To run the code, select some cells you want to merge, press Alt-F8 again and run that macro.

Highlight some cells you want to merge (not dates or currency) and the press Alt+F8 an select this macro. It should (I didn't test) merge the cell contents into a cell without losing any of the contents that were in each cell.
Make sure to insert that code in the file first by pressing Alt+F11 to open VBE and right click the explorer and choose add module. Then paste this code in. Make sure your macro security is low enough to run it.

Related

Batch add a formula in Excel 2016

I have a spreadsheet with hundreds of cells containing formulas like =('Pricing Master'!$E135*'Pricing Master'!$L$29). I would like to batch add the ROUNDUP formula, so that they all read, for example, =ROUNDUP('Pricing Master'!$E135*'Pricing Master'!$L$29,0). A simple Replace All will not work, as it requires both the function call preceding as well as the Number argument following. Not providing both at the same time produces an error. This creates an issue with batch editing using Replace All.
I am sure that there is a way to do this with the Paste Special function, although if there is another way I would be glad to hear it.
My approach is this and I do this often with large sheets with many formulae:
One : select the row(s) or column(s) you want to work with,
Then edit/replace “=(“ with “xyxy(” (I use xyxy as it just doesn’t come up...
Now all replace operations will be quicker as there is no re-calc happening...
So now do edit/replace “xyxy” with “xyxyroundup(“ and “)” with “,0)”
Then just replace “xyxy” with “=“
And wait for it to finish its calculations...
loop through each cell and add formula to the original formula. Like this
Sub updateFor()
Dim r As Range
For Each r In Selection.SpecialCells(xlCellTypeFormulas)''only cells with formula in
r.Formula = "=ROUNDUP(" & Mid(r.Formula, 2) & ",0)"
Next r
End Sub
just replace the selection with the range you want to edit
if you arnt familiar with vba heres a quick guide
press ALT + F11 to show the vba editor
from insert menu select module
module1 should appear in the project window in the top left,
click on this
a large window should open on the right paste the above code in
go back to your worksheet and select the cells you want to roundup
goto to the view ribbon click the macro button on the far right
select the macro 'updateFor' and press run

Microsoft Excel - define a "string" to get specific output

A friend of mine works at Verizon and asked me If excel has built in functions for whenever he types "open" into a cell it will return "8:30-5:00" into that cell.
I hounded google for an hour. I cant seem to find what I am looking for.
Thank you.
You can use Custom functions in Excel. Custom functions, like macros, use the Visual Basic for Applications (VBA) programming language.
https://support.office.com/en-us/article/Create-Custom-Functions-in-Excel-2007-2f06c10b-3622-40d6-a1b2-b6748ae8231f
You need a Worksheet Event Macro. This is a small routine that will constaintly monitor cells on a worksheet and take action if data is typed into them.
Say we want to monitor cell B9. Include the following in the worksheet code area:
Private Sub Worksheet_Change(ByVal Target As Range)
Dim B9 As Range
Set B9 = Range("B9")
If Intersect(Target, B9) Is Nothing Then Exit Sub
If B9.Value <> "Open" Then Exit Sub
Application.EnableEvents = False
B9.Value = "8:30-5:00"
Application.EnableEvents = True
End Sub
Because it is worksheet code, it is very easy to install and automatic to use:
right-click the tab name near the bottom of the Excel window
select View Code - this brings up a VBE window
paste the stuff in and close the VBE window
If you have any concerns, first try it on a trial worksheet.
If you save the workbook, the macro will be saved with it.
If you are using a version of Excel later then 2003, you must save
the file as .xlsm rather than .xlsx
To remove the macro:
bring up the VBE windows as above
clear the code out
close the VBE window
To learn more about macros in general, see:
http://www.mvps.org/dmcritchie/excel/getstarted.htm
and
http://msdn.microsoft.com/en-us/library/ee814735(v=office.14).aspx
To learn more about Event Macros (worksheet code), see:
http://www.mvps.org/dmcritchie/excel/event.htm
Macros must be enabled for this to work!
A non-VBA solution is possible using Excel's built-in Autocorrect facility.
On the File tab in Excel 2013 click Options -> Proofing -> Autocorrect and enter "open" in the Replace: box and "8:30-5:00" in the With: box (without the quotes).
This is not case sensitive so will work for both "open" and "Open".
If you are ever likely to want "open" or "Open" to appear in a string you could add an escape character such as backslash to your replace string "\open".

Is it possible to have a cell which contains a formula and be able to input text into the same cell?

I am trying to create in excel where you enter initials into a cell and the person's full name appears automatically so they do not have to enter their full name every time in a spreadsheet. I have managed to replicate this using nested if statements for different people which works fine but currently it requires two cells and I want to have it on the same cell. I have noticed that if I change the the formula to be in the same cell then it comes up with "circular reference warning" and does not work and if I try to enter text in that cell it replaces the formula. Just wondering is this possible?
=IF(C29="HB", "hazel", IF(C29="AO", "amelia", ""))
You could use Excel's AutoCorrect feature to do this.
Go to File..Options..Proofing -
Click on AutoCorrect Options..
Enter a pair (or triplet) of initials you want to replace and the name you want the initials to be replaced with, then click add. You can then continue adding Replace With definitions.
It doesn't matter if you enter the Replace in lower case "hb" or upper case "HB" because the entry and its replacement are both added to the definitions in lower case.
Excel does this for a reason - it is sensitive to the case of the cell entry. That is to say if you enter "hb" the autocorrect will change this to "hazel"; if you enter "Hb" you will get "Hazel"; and "HB" will give you "HAZEL".
The replacement pairs you enter will only apply to the currently logged username. The replacement pairs will be there every time you open Excel and are available to all open workbooks.
If you want the replacement pairs to be available to other users you will need to:
manually add the replacement pairs to all desired users Excel Options or
develop a macro to add them using Application.AutoCorrect.AddReplacement "hb", "hazel"
If you decide to go down the macro path, you may want to limit the scope of definitions by entering them in certain workbook or worksheet events and consider using the Application.AutoCorrect.DeleteReplacement "hb" method.
Workbook_Open
The replacements will be available to the current user in all workbooks and will remain until the are deleted manually or programmatically.
Workbook_Activate and Workbook_Deactivate
If you use the AddReplacement method in Workbook_Activate and the DeleteReplacement method in Workbook_Deactivate then the replacements will only be available to sheets in the workbook containing the code.
Worksheet_Activate and Worksheet_Deactivate
Place the code in a sheet module within the above sheet event handlers and the replacements will only be available in the sheet corresponding to that module.
This is just an example that you can adapt to your needs. The initials input will be in column A so if the user types JW in a cell in that column, the cell will change to James Ravenswood.
Put the following event macro in the worksheet code area:
Private Sub Worksheet_Change(ByVal Target As Range)
Dim A As Range
ary = Array("JW", "VL", "BJM")
bry = Array("James Ravenswood", "Victor Laszlo", "Bullwinkle J Moose")
Set A = Range("A:A")
If Intersect(Target, A) Is Nothing Then Exit Sub
v = Target.Value
For i = LBound(ary) To UBound(ary)
If v = ary(i) Then
Application.EnableEvents = False
Target.Value = bry(i)
Application.EnableEvents = True
Exit Sub
End If
Next i
End Sub
You would need to fill ary and bry with your initials and names.
Because it is worksheet code, it is very easy to install and automatic to use:
right-click the tab name near the bottom of the Excel window
select View Code - this brings up a VBE window
paste the stuff in and close the VBE window
If you have any concerns, first try it on a trial worksheet.
If you save the workbook, the macro will be saved with it.
If you are using a version of Excel later then 2003, you must save
the file as .xlsm rather than .xlsx
To remove the macro:
bring up the VBE windows as above
clear the code out
close the VBE window
To learn more about macros in general, see:
http://www.mvps.org/dmcritchie/excel/getstarted.htm
and
http://msdn.microsoft.com/en-us/library/ee814735(v=office.14).aspx
To learn more about Event Macros (worksheet code), see:
http://www.mvps.org/dmcritchie/excel/event.htm
Macros must be enabled for this to work!

How to keep nth word of a cell

I want to keep second word of all the cells in a column. Is this possible? I want to do this without using reference.
Column1
hi hello
you me
zero ten
stack overflow
Notice it is just one column. I want to tun this column into:
Column1
hello
me
ten
overflow
Is this something possible? I know how to do it using additional column as reference but not sure how to this job all in one column. I'd appreciate for help.
Without using an extra column, you could do it with VBA. Select the cells you wish to process and run this small macro:
Sub SecondWord()
For Each r In Selection
v = r.Value
If InStr(v, " ") > 0 Then
r.Value = Split(r.Value, " ")(1)
End If
Next r
End Sub
Macros are very easy to install and use:
ALT-F11 brings up the VBE window
ALT-I
ALT-M opens a fresh module
paste the stuff in and close the VBE window
If you save the workbook, the macro will be saved with it.
If you are using a version of Excel later then 2003, you must save
the file as .xlsm rather than .xlsx
To remove the macro:
bring up the VBE window as above
clear the code out
close the VBE window
To use the macro from Excel:
ALT-F8
Select the macro
Touch RUN
To learn more about macros in general, see:
http://www.mvps.org/dmcritchie/excel/getstarted.htm
and
http://msdn.microsoft.com/en-us/library/ee814735(v=office.14).aspx
Macros must be enabled for this to work!

copy text from one excel to another one

I would like to copy the text from a excel file in a specify range to another excel file in the same position
Here is the code that I tried
Sub OneCell()
ChDir "C:\Workfile"
Windows("simple av & cv template(Level).xls").Activate
Sheets("Table ENG SG").Select
Range("C9:C44").Select
Selection.Copy
Windows("Finalize").Activate
Sheets("sheet1").Select
ActiveSheet.Paste
End Sub
Do I need to define sth at the beginning of my program first or did I make any mistakes?
Assuming both your workbooks are open in the same instance of Excel which you can confirm by going to the View tab > Switch Windows and seeing if both workbook names are listed:
Sub ModifiedOneCell()
Workbooks("simple av & cv template(Level).xls").Sheets("Table ENG SG") _
.Range("C9:C44").Copy _
Destination:=Workbooks("Finalize").Sheets("sheet1").Range("C9:C44")
End Sub
The help for this can be found by opening the Object Browser in VBA (press F2), scrolling down to the Range object, clicking Copy from the list in the right pane then press F1.
The [space][underscore at the end of lines is the line continuation key combination in VBA allowing you to split long lines of code for readability.
If your workbooks are open in separate instances of Excel (i.e. only one is visible in Switch Windows), then copying to the clipboard and selecting Windows as you did in your code is the correct approach.
You would need to add
Range("C9:C44").PasteSpecial xlPasteAll
in place of
ActiveSheet.Paste
to get the result into the desired range
Ranges don't have a Paste method - only PasteSpecial.

Resources