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.
Related
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
I need a VBA code that clears only cells containing formulas and skip cells containing values in a given Excel Worksheet.
I have the following Code:
Dim rng As Range, cl As Range
Set rng = ThisWorkbook.Sheets("MATRIX").Range("C2:AU10000")
For Each cl In rng
If cl.Hyperlinks = .Hyperlinks Then
cl.ClearContents
End If
Next cl
Try this approach, please:
If cl.HasFormula Then
cl.ClearContents
End If
This should be the quickest way
rng.SpecialCells(xlCellTypeFormulas).ClearContents
HasFormula vs SpecialCells(xlTypeCellTypeFormulas)
Option Explicit
Sub RemoveHasFormula()
Dim rng As Range, cl As Range
Set rng = ThisWorkbook.Sheets("MATRIX").Range("C2:AU10000")
For Each cl In rng
If cl.HasFormula Then cl.ClearContents
Next cl
End Sub
Sub RemoveSpecialCells()
Dim rng As Range
Set rng = ThisWorkbook.Sheets("MATRIX").Range("C2:AU10000")
rng.SpecialCells(xlCellTypeFormulas).ClearContents
End Sub
Delete formulae via a range's XML structure
For the sake of the art and in order to complete the above solutions I demonstrate a rather unknown approach using a range's xml spreadsheet value (so called ".Value(11)"):
Option Explicit
Sub ExampleCall()
Dim rng As Range: Set rng = Sheet1.Range("a11:b14")
'a) Get range data as xml spreadsheet value
Dim s As String: s = rng.value(xlRangeValueXMLSpreadsheet) ' //or: s = rng.Value(11)
'b) delete formulae and write data back to range
ClearFormulae s ' call sub changing s (By Reference)
rng.value(xlRangeValueXMLSpreadsheet) = s
End Sub
Sub ClearFormulae(s)
'Purpose: delete formulae in xlRangeValueXMLSpreadsheet contents of a given range
'Author : https://stackoverflow.com/users/6460297/t-m
'Date : 2020-07-18
'[1]Set xml document to memory
Dim xDoc As Object: Set xDoc = CreateObject("MSXML2.DOMDocument.6.0")
'[2]Add namespaces.
xDoc.SetProperty "SelectionNamespaces", _
"xmlns:ss='urn:schemas-microsoft-com:office:spreadsheet' " & _
"xmlns:ht='http://www.w3.org/TR/REC-html40'"
'[3]Load cells with formulae into xml document.
If xDoc.LoadXML(s) Then ' load wellformed string content
Dim cell As Object, cells As Object
Set cells = xDoc.SelectNodes("//ss:Cell[#ss:Formula]") ' XPath using namespace prefixes
For Each cell In cells
cell.RemoveAttribute ("ss:Formula")
cell.SelectSingleNode("ss:Data/#ss:Type").Text = "String"
cell.SelectSingleNode("ss:Data").Text = ""
Next cell
'[4] return xml as string content
s = xDoc.XML
End If
End Sub
Further hint to Example call
Instead of replacing the same range, you can also copy the whole data set (including formats) to another sheet via:
Sheet2.Range("D2").Resize(rng.Rows.Count, rng.Columns.Count).value(11) = s
Caveat
As #ChrisNeilson pointed out,
"this can also gives unexpected results in some circumstances
where the range being processed by ClearFormulae includes some cells
that contain formula referring to cells outside the range being processed".
Testing Value(11) against other solutions
Testing with a 20% formula rate (in a double column range) shows that the SpecialCells approach (posted by #Storax and #VBasic2008) starts extremely fast, but looses against my Value(11) approach as soon as the data range exceeds ~ 115,100 rows.
The HasFormula solution (#FaneDuru) seems to be restricted to smaller ranges getting soon time consuming at ranges over 10000 rows.
I would like to have a button in my Excel sheet that:
1) Asks me to select the range I want to use
2) Changes the blank cells found in this range to a fixed value ("NA")
I could find how to get a box asking me to select a range, but not a solution on changing the values in combination with this box.
You can use SpecialCells() to do this in only two lines:
Sub t()
Dim rng As Range
Set rng = Application.InputBox("Select a range", Type:=8).SpecialCells(xlCellTypeBlanks)
rng.Value = "NA"
End Sub
Just pass the range from your other existing get range value from a sub to a sub like this:
Private Sub BlankToNA(Target as Range)
Target.SpecialCells(xlCellTypeBlanks).Value = "NA"
End Sub
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.
I'd like to create a macro that selects a rectangular range of cells and sets the name of every one of those cells to the value/contents of the cell.
In terms of what I've thought so far, I get an error though with the cell.Name line.
Public Sub NameCell()
Dim rng As Range
Dim cell As Range
Set rng = Range("A1:D1")
For Each cell In rng
cell.Name = CStr(cell.Value)
Next
End Sub
Is this what you meant?
Sub setVal()
Range("A1:C6").Select
Selection = "value"
End Sub
I believe this may work for you unless I also misunderstood the question.
Dim r As Range
Dim cell As Range
Set r = Sheet1.UsedRange
For Each cell In r
Sheet1.Names.Add Name:=cell.Value, RefersTo:=cell
Next
Keep in mind, though, that you would want to check that the cell.Value is valid (no spaces, etc.) for a named range.
To replace a range of cells with their values (removing any formulas from the range), you would use something like this.
Public Sub NameCell()
Dim rng As Range
Set rng = Range("A1:D1")
rng.Value = rng.Value
End Sub