简体   繁体   中英

Start on first blank row and declaring variable for counter in For..Next Loop in VBA

The code below is a simple formula repeater. I had one that worked fine, but I want to move away from select and activate and start declaring variables so code is easier to read.

I basically want to press my shortcut and have the code start from the first blank row in column F (starting from F4). Then I want the code to enter a formula using values in this format: Formula( ValueTwoColumnsLeft, ValueOneColumnLeft).

The thing I really need help on is understanding For..Next loops. For the part For StartCell = 1 To 2500 , I do not understand what the i is supposed to be or how I should define it. I know it can't be a range, then it doesn't make sense anymore.

Sub FormulaRepeater()

' Keyboard Shortcut: Ctrl+q
Dim sht As Worksheet
Dim Address As Range
Dim rowcount As Long
Dim Latitude As String
Dim Longitude As String
Dim result As String
Dim StartCell As Range

Set sht = Worksheets("S2")
Set Address = sht.Range("F4").End(xlDown)

rowcount = sht.Cells(Rows.Count, Address) 'start from first blank row in F
Set StartCell = sht.Cells(rowcount + 1, Address)

Latitude = Cells.Offset(0, -2).Value ' get latitude 2 cells to the left
Longitude = Cells.Offset(0, -1).Value 'get longitude 1 cell to the left
'Would using offset here be the same as select i.e. sets Application.ScreenUpdating=True

For rowcount = StartCell To 10 'from the selected cell to 2500, _
which is the daily limit for the Google API

        result = GEOAddress(Latitude, Longitude)


    Next
End Sub

PS don't worry about the formula itsel, it works on it's own. Yes I can drag it down but I am trying to practice. Getting type mismatch on defining rowcount ATM.

Hope you are looking for this

Sub FormulaRepeater()
    Dim sht As Worksheet
    Dim rowcount As Long
    Dim Latitude As String
    Dim Longitude As String
    Dim result As String
    Dim StartCell As Long
    Set sht = Worksheets("S2")
    StartCell = sht.Range("F4").End(xlDown).Row
    rowcount = sht.Range("F" & Rows.Count).End(xlUp).Row 'start from first blank row in F
    For i = StartCell To rowcount
        Latitude = sht.Range("F" & i).Offset(0, -2).Value ' get latitude 2 cells to the left
        Longitude = sht.Range("F" & i).Offset(0, -1).Value 'get longitude 1 cell to the left
        result = GEOAddress(Latitude, Longitude)
    Next
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