Vlookup在循环过程中更改保存文件名VBA

时间:2016-02-05 15:57:43

标签: excel vba excel-vba vlookup

全部 - 我正在寻找一个循环,我可以根据它在循环中运行的值来更改文件名和文件夹位置。例如,如果我从单元格G2:G7运行宏,当进程从G2移动到G3时,我希望文件名和文件夹位置根据某个引用表(查看图像以获取详细信息)进行更改。实际上,我希望文件名和foldername能够查找基金类型。

Public Sub Get_File()

    Dim sFiletype As String
    Dim sFilename As String     'Save the file as this name, if "" then default
    Dim sFolder As String       'Save to this folder, if "" then default
    Dim bReplace As Boolean     'To replace the existing file or not
    Dim sURL As String          'The URL to the location to extract information
    Dim cell, Rng As Range
    Dim sheet As Worksheet

    'Initialize variables

    Set Rng = Range("I2:I10")
    Set sheet = ActiveWorkbook.Sheets("Macro_Button")

    For Each cell In Rng
        If cell <> "" Then
        sFiletype = cell.Value
        sFilename = sFiletype & "_" & Format(Date, "mmddyyyy")

        sFolder = Application.WorksheetFunction.VLookup(sFiletype, sheet.Range("G2:J10"), 4, False)
        bReplace = True
        sURL = "www.preqin.com"

        'Download using the desired approach, XMLHTTP / IE
        Call Download_Use_IE(sURL, sFilename, sFolder, bReplace)

        Else
        Exit Sub
        End If
    Next

End Sub

感谢大家的意见!

http://i.stack.imgur.com/M6GSs.png

2 个答案:

答案 0 :(得分:0)

其中存在VLookUp的限制,其中匹配必须与最左边的列对齐,并且只搜索到右边。正如popular web search中所建议的那样,考虑一个Index/Match替换,它将列与列进行比较并返回匹配行(在任何方向上)的值:

sFolder = Application.WorksheetFunction.Index(sheet.Range("G2:J10"), _
              Application.WorksheetFunction.Match(sFiletype, sheet.Range("I2:I10"), 0), 4)

如果需要使用VLookUp(),则需要减少查找范围:

sFolder = Application.WorksheetFunction.VLookup(sFiletype, sheet.Range("I2:J10"), 2, False)

答案 1 :(得分:0)

除了vlookup之外,我建议将确切的文件夹放入代码中,因为您只有8个选项。这使得调试变得非常明显。您可以通过case语句执行此操作。有关详细信息,请参阅here

Select Case sFilename

Case abc
    sFolder = "C:\One\"
Case def
    sFolder = "C:\Two\"
Case ghi
    sFolder = "C:\Three\"
'so forth for 8 cases...

End Select