Store location of cell address to variable in VBA

只愿长相守 提交于 2019-12-02 02:04:29

The .Address property returns a string so you'll need to to set the addCell variable like so:

Set addCell = Worksheets("Schedule").Range(.Address)

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!