在VBA中循环一个宏

时间:2014-01-29 12:36:15

标签: excel excel-vba vba

我将宏进一步访问和API。我在列A中有地址,在列B中有邮政编码。如果我选​​择C1并激活宏,它将查找地址+邮政编码并返回结果。但是,我希望它自动为后续行执行此操作。因此,在C1中查找A1和B1得到结果后,我希望它查找A2和B2,并在C2中给出结果,依此类推,只要我想要...

我该怎么做?

宏:

Sub APIExecute()
'
' APIExecute Macro
'
' Keyboard Shortcut: Ctrl+Shift+Q
'
    Dim connectionString As String, quertable As QueryTable
    connectionString = "URL;https://www.conzoom.eu/Webservices/GetMosaic.aspx?address=" & _
    ThisWorkbook.Sheets("Input").Range("A1") & "&postcode=" & ThisWorkbook.Sheets("Input").Range("B1")


    Set quertable = ActiveSheet.QueryTables.Add(Connection:=connectionString, Destination:=ActiveCell)
    With quertable
        .FieldNames = False
        .RowNumbers = False
        .RefreshOnFileOpen = False
        .RefreshStyle = xlOverwriteCells
        .SavePassword = False
        .SaveData = False
        .BackgroundQuery = False
        .AdjustColumnWidth = False
        .RefreshPeriod = 0
        .WebSelectionType = xlEntirePage
        .WebFormatting = xlWebFormattingNone
        .WebConsecutiveDelimitersAsOne = True
        .WebSingleBlockTextImport = False
        .WebDisableDateRecognition = False
        .WebDisableRedirections = False
        .MaintainConnection = False
        .WebPreFormattedTextToColumns = True
        .Refresh
    End With

End Sub

1 个答案:

答案 0 :(得分:0)

简单的方法是使用For-Next循环。

首先将For i=1 to x添加到sub的开头,其中x是您需要的行数。然后,只需将Range("A1")更改为Range("A" & i),将B1更改为相同。

最后,通过将C更改为Destination:=ActiveCell来选择Destination:=Range("C" & i)范围,并在Next i

之后加上End With