Could you please help me with this Excel Visual Basic Please make sure you did t
ID: 3818038 • Letter: C
Question
Could you please help me with this Excel Visual Basic
Please make sure you did the problem correctly
Problem 7
1. Write a macro that swaps two selected cells. The cells can be next to each other horizontally or vertically. In order to make this macro work, you must determine which orientation the selection is in. To do so, you can just compare the number of rows in the Selection to the number of columns. Also, verify that exactly two cells have been selected (usingSelection.count). If exactly two cells have not been selected, use a message box to show the user an error and then quit your macro.
2. In order to swap the values, you will need to create a temporary value... but you won't know what type of data the cells hold, so you must use a Variant type. A Variant type 'varies' to take any type of data.
3. Test your function with both vertically and horizontally selected cells, containing both numbers and strings. Also test with Selections of 1 and 3+ cells.
4. Once you have tested your macro, iconify the Visual Basic window, and on a sheet of paper, re-write this macro by hand.
5. Bring the Visual Basic window back up and compare your work. Mark on your sheet of paper anything that you did wrong.
Explanation / Answer
or if two non-adjoining cells are there
Sub SwapContent()
If Selection.Count <> 2 Then
MsgBox "Please select two cell to swap either horizontally or vertically ."
Exit Sub
End If
Dim range1 As Range, range2 As Range
Dim num1 As Variant, num2 As Variant
xTitleId = "SwapContent"
Set range1 = Application.Selection
Set range1= Application.InputBox("Range1:", xTitleId, range1.Address, Type:=8)
Set range2 = Application.InputBox("Range2:", xTitleId, Type:=8)
Application.ScreenUpdating = False
num1 = range1.Value
num2 = range2.Value
range1.Value = num2
range2.Value = num1
Application.ScreenUpdating = True
End Sub