View Single Post
 
Old 08-05-2023, 08:09 PM
soroush.kalantari soroush.kalantari is offline Windows 10 Office 2016
Competent Performer
 
Join Date: Jun 2021
Posts: 124
soroush.kalantari is on a distinguished road
Default

Quote:
Originally Posted by p45cal View Post
See attached and comments in code.
Code:
Sub pasttojustvisblecells()
Application.DisplayAlerts = False
Dim AtLeast1CellVisible, ws As Worksheet, rng As Range, rng1 As Range, cll, i As Long

Dim ws1 As Worksheet
Set ws = ActiveSheet
Set rng = Selection
'This next section is to cater for when only one cell is selected on the destination sheet; if only one cell is selected
'.SpecialCells includes all the visible cells on the entire worksheet!
'*********************
For Each cll In rng.Cells 'this loop ensures at least one cell in the selection is visible.
  If Not (cll.EntireColumn.Hidden Or cll.EntireRow.Hidden) Then
    AtLeast1CellVisible = True
    Exit For
  End If
Next cll
'*********************

If AtLeast1CellVisible Then
  If rng.Cells.Count = 1 Then Set rng = Selection Else Set rng = rng.SpecialCells(xlCellTypeVisible)
'  MsgBox rng.Address
  Set ws1 = Sheets.Add ' After:=ActiveSheet 'I'm not sure why you do this…
  ws1.Cells(1).PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
  Set rng1 = Selection

  i = 0
  For Each cll In rng
    i = i + 1
    cll.Value = rng1.Cells(i).Value
  Next cll

  ws1.Delete
  'ws.Activate 'shouldn't need this
Else
  MsgBox "No visible cells selected to paste to" 'this could happen if you hid all selected cells.
End If
Application.DisplayAlerts = True
End Sub
Thank you for your complete and constructive answer which solved my problem. I added a new worksheet because without this, I didn’t know how to set rng1. Do you know a way to use copied data in this code without adding new worksheet? Can you tell me why the line “rng.Cells(i).Select” in my code failed? (these questions are just for improving my understanding of vba)
Reply With Quote