Only copy visible range in VBA?

后端 未结 4 1874
情话喂你
情话喂你 2021-01-15 12:52

I\'m running into an issue where I\'m unable to copy only visible cells to a new sheet. I\'m able to get the lastrow, but I get #N/A on every cell except the first for each

4条回答
  •  醉梦人生
    2021-01-15 13:20

    To define whether a cell is visible or not, both its column and row should be visible. This means, that the .Hidden property of the column and the row should be set to False.

    Here is some sample code of how to copy only the visible ranges between two worksheets.

    Imagine that you have an input like this in Worksheets(1):

    Then you manually hide column B and you want to get in Worksheets(2) every cell from the Range(A1:C4), without the ones in column B. Like this:

    To do this, you should check each cell in the range, whether its column or row is visible or not. A possible solution is this one:

    Sub TestMe()
    
        Dim myCell  As Range
        For Each myCell In Worksheets(1).Range("A1:C4")
            If (Not Rows(myCell.Row).Hidden) And (Not Columns(myCell.Column).Hidden) Then
                Dim newCell As Range
                Set newCell = Worksheets(2).Cells(myCell.Row, myCell.Column)
                newCell.Value2 = myCell.Value2
            End If
        Next myCell    
    End Sub
    

    Just a general advise - whenever you use something like this Range("A1").Value2 = Range("A1").Value2 make sure that both are the same and not the left is Value2 and the right is .Value. It probably will not bring what you are expecting.

提交回复
热议问题