2016-02-05 35 views
-1

全部 - 我正在尋找一個循環,我可以根據它在循環中運行的值更改文件名和文件夾位置。例如,如果我正在從單元格G2:G7運行宏,當進程從G2移動到G3時,我希望文件名和文件夾位置根據某個參考表(詳情請查看圖像)進行更改。實際上,我希望文件名和文件夾名稱是查找基金類型。Vlookup在循環過程中更改保存文件名VBA

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

+0

您能否將此代碼縮小到您遇到問題的確切區域? SO鼓勵[最小,完整和可驗證示例](http://stackoverflow.com/help/mcve),但也建議指出相關部分。 – Parfait

+0

http://stackoverflow.com/users/1422451/parfait - 上面是我正在處理,但這似乎並沒有工作。我目前卡在vlookup行,並不斷獲得運行時錯誤'1004'無法獲得工作表功能類的vlookup屬性 –

回答

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) 
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