Store location of cell address to variable in VBA

后端 未结 3 1940
没有蜡笔的小新
没有蜡笔的小新 2021-01-22 22:29

I\'m using VBA in Excel and I\'m using a function to find the first empty row then adding some values, after that I need to pass the address of the cell to another function but

3条回答
  •  礼貌的吻别
    2021-01-22 22:49

    You do not need to overcomplicate the code with something like Set addCell = Worksheets("Schedule").Range(.Address) because it really makes the readability a bit tough. In general, try something as simple as this: Set FirstEmptyRow = myCell. Then the whole code could be rewritten to this:

    Public Function FirstEmptyRow() As Range
    
        Dim myCell As Range
        Dim coltoSearch As String, lastRow As String
        Dim wks As Worksheet
    
        Set wks = Worksheets(1)
        coltoSearch = "A"
    
        Dim i As Long
        For i = 3 To wks.Range(coltoSearch & Rows.Count).End(xlUp).Row
            Set myCell = sheet.Range(coltoSearch & i)
            If IsEmpty(myCell) Then
                Set FirstEmptyRow = myCell
                Exit For
            End If
        Next i
    
        If i = 2 ^ 20 Then
            MsgBox "No empty rows at all!"
        Else
            Set FirstEmptyRow = sheet.Range(coltoSearch & i + 1)
        End If
    
    End Function
    

    The last part of the code makes sure, that if there is no empty cell before the last row and row number 3, then next cell would be given as an answer. Furthermore, it checks whether this next row is not the last row in Excel and if it is so, it gives a MsgBox() with some information.

提交回复
热议问题