Home » excel » excel – Macro to delete contents of cells using their references

excel – Macro to delete contents of cells using their references

Posted by: admin May 14, 2020 Leave a comment

Questions:

I have a list of references of cells to be deleted. The list of references is in sheet “test_url”. The list of references point to cells to be deleted that are in another sheet “main_lists”.

What I am after is a macro that takes all the references listed in “test_url” sheet, and select their cells in “main_lists” sheet and delete them.

The following macro is what I recorded for two references only in an attempt to demonstrate my problem that necessitated me to copy the reference from “test_url” sheet, then paste it in the NameBox of “main_urls” sheet to select the contents of the designated cell then delete its contents. This process was done manually one cell at a time for a list of 10-20 addresses/references. However, recently this list is over 2000 entries and it is growing:

Sub DeletePermittedCells()
'DeletePermittedCells Macro
Sheets("test_urls").Select
Range("B2").Select
Sheets("test_urls").Select
Selection.Copy
Sheets("main_lists").Select
Application.Goto Reference:="R200045C1"
Application.CutCopyMode = False
Selection.ClearContents
Sheets("test_urls").Select
Range("B3").Select
Selection.Copy
Sheets("main_lists").Select
Application.Goto Reference:="R247138C1"
Application.CutCopyMode = False
Selection.ClearContents
Sheets("test_urls").Select
End Sub

Can someone help with this issue please?

How to&Answers:

Try this one:

Sub DeletePermittedCells()
    Dim rng As Range
    Dim arr, c

    With Sheets("test_urls")
        'storing data in array makes your code much faster
        arr = .Range("B2:B" & .Cells(.Rows.Count, "B").End(xlUp).Row).Value
    End With

    With Sheets("main_lists")
        Set rng = .Range(arr(1, 1))
        For Each c In arr
            Set rng = Union(rng, .Range(c))
        Next
    End With

    rng.ClearContents
End Sub

storing addresses in array (rather than reading each cell from worksheet directly) makes your code much faster.

Note, code assumed that your addresses stored in range B2:B & lastrow where lastrow – is row of last cell with data in column B

Answer:

This assumes that the list of cells to be cleared in is column A:

Sub ClearCells()
    Dim s1 As Worksheet, s2 As Worksheet
    Dim N As Long, I As Long, addy As String
    Set s1 = Sheets("test_url")
    Set s2 = Sheets("main_lists")
    N = s1.Cells(Rows.Count, "A").End(xlUp).Row
    For I = 1 To N
        addy = s1.Cells(I, 1).Value
        s2.Range(addy).ClearContents
    Next I
End Sub