Copying the selection and later pasting it - excel

I need to store the selected cells and use their values in future. I am storing the the selection to a variable of range object and then i am modifying the selected cells. I am checking the results in other subroutine and if condition is false then i need to restore the values on the same range as it was previously.
Public hi, hj As Integer
Public ActSheet As Worksheet
Public SelRange As Range
Sub per_num()
Dim cell As Object
Set ActSheet = ActiveSheet
Set SelRange = Selection
SelRange.Copy
For Each cell In Selection
'perform some action
Next cell
hi = Selection.Row
hj = Selection.Column
End Sub
Sub num_per()
if something is false
Cells(hi, hj).Select
SelRange.PasteSpecial xlPasteFormats
End Sub

Your range creates a reference to that group of cells. What you are asking requires you to write the values into memory. This should do what you are asking:
Option Explicit
Public selArray As Variant ' Add this global variable
Public SelRange As Range
Sub per_num()
Dim cell As Range
Set SelRange = Selection
selArray = SelRange ' Returns the values from your range into a variant
For Each cell In Selection
'perform some action
Next cell
End Sub
Sub num_per()
' if something is false
SelRange = selArray ' Writes the values from the variant back into the range
Set SelRange = Nothing
If IsArray(selArray) Then Erase selArray
End Sub
In the per_num sub, it creates the reference to your selection and writes the values into the selArray variable.
In the num_per sub it writes the values back into the cells referred to by your range.
*It is worth noting that selArray won't actually be an array if you have only selected one cell, the naming was just a hangover from my initial attempt.

Related

Copy_Paste_Visible_Cells_Only

I have been trying to Copy the Filtered data and pasting the data on filtered cell but my code is not working.
I have data in Range Sheet2.Range("O2:O10000") and i filtered this range to Sheet2.Range("O173:O2400").
I want to copy the data from filtered cells Sheet2.Range("O173:O2400") then paste this data to visible cells on same Sheet2.Range("N173:N2400")
Please note there are multiple hidden rows in this range.
Any help will be appreciated
Sub Copy_Paste__Visible_Cells_Only()
Sheet2.Range("O173:O2400").SpecialCells(xlCellTypeVisible).Copy
Sheet2.Range("N173:N2400").SpecialCells(xlCellTypeVisible).Paste
End Sub
In this case, pasting won't work. As far as I know, you can't change the paste behaviour to only paste to visible cells.
When you select visible cells only, you get a collection of areas (you can think of them as a discontinuous set of ranges). Given you're just trying to move your visible data to the left, you can do it by looping through the areas and assigning their values to the same area in the previous column. Something like this:
Public Sub CopyVisible()
Dim a As Range
For Each a In Sheet1.Range("O4:O17").SpecialCells(xlCellTypeVisible).Areas
a.Offset(0, -1).Value = a.Value
Next
End Sub
The .Offset(0,-1) is signalling that you wish the values to be moved one column to the left
You can see from this example, when I filter on "a" in column O and run the macro, only the "a" values are moved to column N.
I would use a generic sub copyVisibleCellsToOtherColumn to which you pass the source-range and the target-start range.
Advantage you can re-use it for different scenarios.
Sub test_CopyVisibleCells()
Dim rgSource As Range
Set rgSource = sheet2.Range("O173:O2400")
Dim rgTarget As Range
Set rgTarget = sheet2.Range("N173:02400")
copyVisibleCells rgSource, rgTarget
End Sub
'this ist the generic sub
Public Sub copyVisibleCellsToOtherColumn(rgSource As Range, rgTarget As Range)
Dim c As Range, a As Range
For Each a In rgSource.Areas
'this will return the visible cells within rgsource
For Each c In a.Cells
rgTarget.Rows(c.Row).Value = c.Value
Next
Next
End Sub
I found code from somewhere which able to copy visible cells and paste into visible cells. For easy usage, I manually assign a shortcut ctrl+shift+C to call the macro.
Public Sub Copy_Range_Paste_Into_Visible_Cells()
'Sub Copy_Range_Paste_Into_Visible_Cells()
Dim rngSource As Range, rngDestination As Range, cell As Range, cc As Long, i As Long
On Error Resume Next
Application.DisplayAlerts = False
Set rngSource = Application.InputBox("Select the filtered range to copy. ", "Select Filtered Cells", Type:=8)
If rngSource Is Nothing Then Application.DisplayAlerts = True: Exit Sub 'User canceled
Set rngDestination = Application.InputBox("Select the destination cell to paste to. ", "Select Paste Destination", Type:=8)
If rngDestination Is Nothing Then Application.DisplayAlerts = True: Exit Sub 'User canceled
On Error GoTo 0
Application.DisplayAlerts = True
cc = rngSource.Columns.Count
For Each cell In rngSource.Columns(1).SpecialCells(xlCellTypeVisible)
Do Until Not rngDestination(1).Offset(i).EntireRow.Hidden
i = i + 1
Loop
rngDestination(1).Offset(i).Resize(1, cc).Value = cell.Resize(1, cc).Value
i = i + 1
Next
End Sub

How to refer to a selected block of cells in vba excel

How to refer in the code to the selected range of cells in the active sheet.
To clarify, I am not asking how to select a range of cell.
Is there any ActiveRange ActiveRegion or something?
I haven't found it...
For example, (not working) here is a simple sub:
Sub test()
Dim region, cel As Range
region = ActiveCell.CurrentRegion
For Each cel In region
cel = 1
Next cel
End Sub
A couple of remarks:
Define all the variables types and Selection is already a Range if a Range is selected. Beware that it may return other objects, so you should check the type of object returned before working with it
Read this
Public Sub LoopActiveRange()
Dim sourceCell As Range
For Each sourceCell In Selection
sourceCell = 1
Next sourceCell
End Sub
To work with Selected cells use Selection property (Excel) MSDN
Example
Option Explicit
Public Sub Example()
Dim rng As Range
For Each rng In Selection
DoEvents
rng.Value = "value" ' adds a to all selected cells
Next
End Sub
Remarks The returned object type depends on the current selection (for example, if a cell is selected, this property returns a Range object). The Selection property returns Nothing if nothing is selected.

How to toggle checkboxes that are linked to a specific range?

I have checkboxes that are LINKED to their own respective cells. When I check checkbox1, I want all the checkboxes in a specific range to be checked/unchecked.
Here is what I Used but it's not working. It's giving me error Object variable or With block variable not set.
Sub SelectAll_Click()
Dim xCheckBox As CheckBox
Dim rng As Range, cell As Range
Set rng = Range("B19:B28")
For Each cell In rng
If xCheckBox.Name <> Application.ActiveSheet.CheckBoxes("Check Box 1").Name Then
xCheckBox.Value = Application.ActiveSheet.CheckBoxes("Check Box 1").Value
End If
Next cell
End Sub
Thank you
To toggle a checkbox that is linked to a cell you can simply set the cell value (or return value from a formula) to either True or False.
Using your example it would look something like:
Sub SelectAll_Click()
Dim xCheckBox As CheckBox
Dim rng As Range, cell As Range
Set rng = Range("B19:B28")
For Each cell In rng
cell.value = True
Next cell
End Sub
If you need logic based on the checkbox itself then you would instead loop the checkboxes rather than the a range.
Private Sub demoLoopingCheckboxes()
Dim control As OLEObject
For Each control In ActiveSheet.OLEObjects
With control
' The type of activex control
' Use this is a if statement to limit to only "CheckBox"
Debug.Print TypeName(.Object)
' The cell Address to the linked cell
Debug.Print .LinkedCell
' Can read/write the value to the checkbox itself
Debug.Print .Object.Value
End With
Next control
End Sub

Hide all Rows except matching value

I'm working with some data in excel spanning B9:AJ1108 - so multiple rows and columns. I am looking to hide all rows except where the value in column B matches the number in cell C5.
I've tried multiple and can only just about get everything to hide but the unhiding is the issue. I understand how to hide all and how to unhide all. What I need help with is how to hide all and then unhide if something matches the value in C5.
Code so far:
Private Sub CommandButton2_Click()
Worksheets("Employee information").Range("B9:B1108").Rows.Hidden = False
End Sub
Private Sub CommandButton1_Click()
Worksheets("Employee information").Range("B9:B1108").Rows.Hidden = True
'Need to put in the argument to search for C5 value
End Sub
I would also like this to be button controlled but I don't know if that is a case of creating a module or just code within the sheet?
For unhiding the rows you can use "Rows.EntireRow.Hidden = False"
If you want to use a button for the macro to get executed, create a button and excel will ask you which macro you want to get when you click the button.
value= Worksheets("Employee information").cells(5,3).value
That will give you the value of the cell C5, now you need to go through the rows and look for this value.
Hide Rows Not Containing Criteria in Column
Private Sub CommandButton1_Click()
With Worksheets("Employee information")
' Define Criteria (restrict to numbers).
Dim Criteria As Variant
Criteria = .Range("C5").Value
If Not IsNumeric(Criteria) Then
Exit Sub
End If
' Define Criteria Range.
Dim rng As Range
Set rng = .Range("B9:B1108")
End With
' Declare additional variables.
Dim hRng As Range ' Hide Range
Dim cel As Range ' Current Cell (in Source Range)
Dim CurVal As Variant ' Current Value (of Current Cell in Source Range)
' Create a union (Hide Range) of all the cell ranges
' that do not contain Criteria.
For Each cel In rng.Cells
' Evaluate Current Value.
CurVal = cel.Value
If IsNumeric(CurVal) Then
If CurVal = Criteria Then
GoTo NextCell ' Match found: do nothing.
End If
End If
' Match not found: add Current Cell to Hide Range.
If Not hRng Is Nothing Then
Set hRng = Union(hRng, cel)
Else
Set hRng = cel
End If
NextCell:
Next cel
' Hide rows of Hide Range.
If Not hRng Is Nothing Then
hRng.Rows.Hidden = True
End If
End Sub

How to loop over collection of textbox and range

I'm new to vba and I can't manage to do what I want although it's very simple.
I need to automatically add textbox values from a userform to my second sheet. For example in each textboxes I provide an integer and I want to put this values 1 by 1 on the range C5:C52.
I have the following code that loop trough my textbox collection and range C5:C52
Sub remplissageTab()
Dim rng As Range
Dim cell As Range
Set rng = Sheets("Câbles").Range("C5:C52")
For Each txtBox In clcTxt
For Each cell In rng
cell.Value = CInt(txtBox)
Next cell
Next txtBox
Unload Me
End Sub
However the results is not what I expect. It only prints the last textbox value through all ranges. But I want all values in the same order textboxes are created.
I hope I made clear explanations.
What do you think ?
Thanks a lot for your help. Lyess
Like so:
Sub remplissageTab()
Dim rng As Range
Dim Rw as Long
Set rng = Sheets("Câbles").Range("C5:C52")
For Each txtBox In clcTxt
rng.Offset(Rw).Value = CInt(txtBox)
Rw = Rw + 1
Next txtBox
Unload Me
End Sub

Resources