Search code examples
excelvba

Database from a different Sheet


I'm trying to get all the data from cell range C6:K105 from Sheet1 and save it to Sheet14 but I'm only getting results from cell range C6:C14. Can anyone help me with this VBA code? Thanks

This is the macro VBA code I'm trying to create.

Sub Save()

    Set Database = Sheet14.Range("A1:I1")
    Set New_Input = Sheet1.Range("C6:K105")

    Last_Row = Database.Rows.Count + 1
    
    While Database.Cells(Last_Row, 1) <> ""
        Last_Row = Last_Row + 1:
    Wend
    
    For i = 1 To New_Input.Rows.Count
        If New_Input.Cells(i, 1) <> "" Then
            New_Data = New_Input.Cells(i, 1)
            Database.Cells(Last_Row, i) = New_Data
        End If
    Next i

End Sub

Solution

  • Copy Matching Rows

    Option Explicit
    
    Sub CopyNonBlankRows()
        
        Const CRITERIA_COLUMN As Long = 1
        
        ' Source
        
        Dim Data() As Variant, sr As Long, dr As Long, cCount As Long, c As Long
        
        With Sheet1.Range("C6:K105")
            ' Write range values to array.
            Data = .Value
            ' Move matching (not blank) rows to the top of the array.
            cCount = .Columns.Count
            For sr = 1 To .Rows.Count
                If Len(CStr(Data(sr, CRITERIA_COLUMN))) > 0 Then ' is not blank
                    dr = dr + 1
                    For c = 1 To cCount
                        Data(dr, c) = Data(sr, c)
                    Next c
                End If
            Next sr
            ' Check if no matching rows.
            If dr = 0 Then
                MsgBox "All cells are blank in range """ _
                    & .Columns(CRITERIA_COLUMN).Address(0, 0) & """ of sheet """ _
                    & .Worksheet.Name & """!", vbExclamation
                Exit Sub
            End If
        End With
        
        ' Destination
        
        Dim drrg As Range, dlcell As Range
        
        ' Reference the first 'available' row.
        With Sheet14.Range("A1").Resize(, cCount)
            Set drrg = .Rows(1)
            Set dlcell = .Resize(.Worksheet.Rows.Count - .Row + 1) _
                .Find("*", , xlFormulas, , xlByRows, xlPrevious)
            If Not dlcell Is Nothing Then
                Set drrg = drrg.Offset(dlcell.Row - .Row + 1)
            End If
        End With
        
        ' Copy values from the top of the array to the destination range.
        drrg.Resize(dr).Value = Data
        
        ' Inform.
        MsgBox "Data copied.", vbInformation
        
    End Sub