从第一个空白行开始,并在VBA中的For..Next循环中为计数器声明变量

时间:2016-04-13 04:56:49

标签: excel vba excel-vba

以下代码是一个简单的公式转发器。我有一个工作正常但我想离开selectactivate并开始声明变量,因此代码更容易阅读。

我基本上想按下我的快捷方式,让代码从F列的第一个空白行开始(从F4开始)。然后我希望代码使用以下格式的值输入公式:公式(ValueTwoColumnsLeft,ValueOneColumnLeft)。

我真正需要帮助的是理解For..Next循环。对于For StartCell = 1 To 2500部分,我不明白i应该是什么或者我应该如何定义它。我知道它不能是一个范围,那就再也没有意义了。

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

P.S不要担心配方itsel,它可以自己工作。是的我可以拖下来,但我正在努力练习。在定义rowcount ATM时类型不匹配。

1 个答案:

答案 0 :(得分:1)

希望你正在寻找这个

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
相关问题