VBA - 跳过行并覆盖行

时间:2017-07-14 15:45:27

标签: excel vba excel-vba

我对编程非常陌生,但一直在努力学习。我遇到了一个问题,我试图从雅虎财经中提取股票价格,但我需要它跳过第4,6,20,34,41行。这些单元格在C列中也是空白的。我试过用if语句在哪里     如果ws.Range(" K6,K20,K34,K41")。value =""然后退出子
但是这使得整个程序没有运行。 此外,当它运行时,它将创建一个新列,其中前一个" K"专栏是,而不是只是覆盖K,这是我试图做的。

感谢您的帮助!对不起,如果这个问题看起来令人困惑,我在这里澄清任何问题! :)

Sub BtnRefresh()

Dim ws As Worksheet
Dim qt As QueryTable
Dim URL As String    
Dim Symbol As String
Dim i As Integer
Dim Last As Integer
Set ws = Worksheets("Current Portfolio")



Last = ws.Range("C100").End(xlUp).Row

For i = 1 To Last
    Symbol = Symbol & ws.Range("C" & i).Value & "+"

Next i


URL = "http://download.finance.yahoo.com/d/quotes.csv?s=" & Symbol & "&f=l1"

Set qt = ws.QueryTables.Add( _
    Connection:="URL;" & URL, _
    Destination:=Range("K5"))
        qt.BackgroundQuery = True
        qt.SaveData = True

        qt.Refresh BackgroundQuery:=False
        qt.RefreshStyle = xlOverwriteCells



End Sub

3 个答案:

答案 0 :(得分:0)

这应该适用于跳过步骤。

    Sub BtnRefresh()

    Dim ws As Worksheet
    Dim qt As QueryTable
    Dim URL As String
    Dim Symbol As String
    Dim i As Integer
    Dim Last As Integer
    Set ws = Worksheets("Current Portfolio")



    Last = ws.Range("C100").End(xlUp).Row

    For i = 1 To Last

        If i = 4 Or i = 6 Or i = 20 Or i = 34 Then
            'do nothing!
        Else
        Symbol = Symbol & ws.Range("C" & i).Value & "+"

        End If
    Next i


    URL = "http://download.finance.yahoo.com/d/quotes.csv?s=" & Symbol & "&f=l1"

    Set qt = ws.QueryTables.Add( _
        Connection:="URL;" & URL, _
        Destination:=Range("K5"))
            qt.BackgroundQuery = True
            qt.SaveData = True

            qt.Refresh BackgroundQuery:=False
            qt.RefreshStyle = xlOverwriteCells



    End Sub

答案 1 :(得分:0)

对于易于维护的基于排除列表的方法,请将您的FOR.. NEXT循环替换为:

exclude = "4/6/20/34"

For i = 1 To Last
    If InStr(1, "/" & exclude & "/", "/" & Trim(Str(i)) & "/") = 0 Then Symbol = Symbol & ws.Range("C" & i).Value & "+"
Next

至于K列问题,如果您不能发出Refresh因为循环获取的数据可能会发生变化,那么只需清除表格如何:

Range("K:K").ClearContents ' or ("K:N") or whatever depending on width of the table?

答案 2 :(得分:0)

您可以跳过它们,也可以将空格更改为零,例如:

Last = ws.Range("C100").End(xlUp).Row

For i = 1 To Last
     If Cells(i,3).Value=""
         Cells(i,3).Value="0"
         Else
         End If

    Symbol = Symbol & ws.Range("C" & i).Value & "+"

Next i

Range("C4,C6,C20,C34,C41").ClearContents

这使您可以保持符号公式不变。

C中的那些空白单元是否需要保持空白?如果是这样,我可以重新开始工作。

编辑:重新设计以确保这些单元格已删除内容。如果您不需要,请不要将该行添加到.ClearContents。