简体   繁体   中英

How to reference last used column in a certain row and paste certain value in there

I am working on a macro that loops over a the used range in one sheet (which is the last sheet in the workbook) in a certain column ("H"). The macro should then copy the value, only if it is not 0, and paste it in a sheet called "Overview" in the original row, offset by 3 (eg first row becomes 4th row) and in the column behind the last used column in row 5. (I hope that makes sense?). I already worked on some code but I did not manage to reference the last used column correctly and am honestly close to a breakdown.

can someone explain to me what I am doing wrong? This is what I already have:


Dim Cell As Range, cRange As Range, lrw As Long
    Dim wsDestination As Worksheet, wsSource As Worksheet
        
        'set worksheets
        With ThisWorkbook
            Set wsSource = .Worksheets(Sheets.Count)
            Set wsDestination = .Worksheets("Overview")
        End With
        
    
    LastRow1 = wsSource.Cells(Rows.Count, "H").End(xlUp).Row
    LastColumn1 = wsDestination.Cells(5, "A").End(xlRight).Column
    Set cRange = wsSource.Range(wsSource.Cells(1, 8), wsSource.Cells(LastRow1, 8))
    For Each Cell In cRange.Cells
        If Cell.Value > 0 Then wsDestination.Cells(Cell.Row, LastColumn1).offset(3, 1) = Cell.Value
    Next Cell


End Sub```

The Subtle Differences in Ways of Finding the 'Last Column'

  • To successfully test the first procedure, in a new worksheet you have to:

    • write a value in cell A1 ,
    • write ="" in cell B1 ,
    • write a value in cell C1 ,
    • hide column C
    • and use a fill color in cell D1 .
  • The result of the test will be shown in the Immediate window CTRL + G .

  • The third procedure is an example of how to use the second procedure, the function for calculating the column of the last non-blank cell in a row using the Find method.

The Code

Option Explicit

Sub LastColumnSuptileDifferences()
     
     Dim wb As Workbook
     Set wb = ThisWorkbook ' The workbook containing this code.
     Dim ws As Worksheet
     Set ws = wb.Worksheets("Sheet1")
     
     ' Cell Value Comment
     '  A1:  1    Value
     '  B1:  =""  Formula
     '  C1   1    Value: Hidden Column
     '  D1:       Fill Color
     
     Debug.Print ws.Rows(1).Find("*", , xlFormulas, , , xlPrevious).Column ' 3
     Debug.Print ws.Cells(1, ws.Columns.Count).End(xlToLeft).Column        ' 2
     Debug.Print ws.Rows(1).Find("*", , xlValues, , , xlPrevious).Column   ' 1
     
     Debug.Print ws.Rows(1).CurrentRegion.Columns.Count                    ' 3
     Debug.Print ws.Rows(1).SpecialCells(xlCellTypeLastCell).Column        ' 4
     Debug.Print ws.UsedRange.Rows(1).Columns.Count                        ' 4

End Sub

' This will find the last column even if columns are hidden
' unless you set 'excludeEmpties' to 'True'.
' If you set 'excludeEmpties' to 'True', the right-most cells in the row,
' possibly containing a formula that evaluates to "", will be skipped.
' Additionally only the visible cells will be included, i.e. hidden
' right-most columns, possibly containing data in cells of the row,
' will not be considered (mimicking 'End(xlToLeft)' or CRTL+Left).
Function getLastColumnInRow(RowNumber As Variant, _
                            Optional Sheet As Worksheet = Nothing, _
                            Optional excludeEmpties As Boolean = False)
    
    If Sheet Is Nothing Then
        Set Sheet = ActiveSheet
    End If
    
    Dim FormVal As XlFindLookIn
    If excludeEmpties Then
        FormVal = xlValues
    Else
        FormVal = xlFormulas
    End If
    
    Dim rng As Range
    Set rng = Sheet.Rows(RowNumber).Find(What:="*", _
                                         LookIn:=FormVal, _
                                         SearchDirection:=xlPrevious)
    If Not rng Is Nothing Then
        getLastColumnInRow = rng.Column
    Else
        getLastColumnInRow = 0
    End If
    
End Function

Sub testgetLastColumnInRow()
    '...
    
    LastColumn1 = getLastColumnInRow(5, wsDestination)
    If LastColumn1 = 0 Then
        MsgBox "No Data.", vbExclamation, "Empty Row"
        Exit Sub ' or whatever
    End If
    
    ' Continue with code.
    Debug.Print LastColumn1
    
    '...
End Sub

So you didn't quite get the last column right. Here's it back.

Dim Cell As Range, cRange As Range, lrw As Long
    Dim wsDestination As Worksheet, wsSource As Worksheet
        
        'set worksheets
        With ThisWorkbook
            Set wsSource = .Worksheets(Sheets.Count)
            Set wsDestination = .Worksheets("Overview")
        End With
        
    
    LastRow1 = wsSource.Cells(Rows.Count, "H").End(xlUp).Row
    LastColumn1 = wsDestination.Cells(5, columns.count).End(xltoleft).Column
    Set cRange = wsSource.Range(wsSource.Cells(1, 8), wsSource.Cells(LastRow1, 8))
    For Each Cell In cRange.Cells
        If Cell.Value > 0 Then wsDestination.Cells(Cell.Row, LastColumn1).offset(3, 1) = Cell.Value  
    Next Cell


End Sub```

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM