2016-04-01 56 views
2

有人可以幫助我,因爲我拉我的頭髮。我試圖從網站&下載一個文件,將它複製到另一個位置。如果我使用下面註釋的實際文件名稱,它將起作用。可悲的是,文件名稱每天都在變化&我已經在單元格B1(01 04 2016)中說明了這一點。無論如何,我收到'編譯錯誤:需要常量表達式'的錯誤,並突出顯示第一個'&'。有沒有人有任何想法可能有幫助?VBA從文件名不斷變化的URL下載文件

{

Option Explicit 

Private Declare Function URLDownloadToFile Lib "urlmon" Alias _ 
              "URLDownloadToFileA" (_ 
              ByVal pCaller As Long, ByVal szURL As String, _ 
              ByVal szFileName As String, _ 
              ByVal dwReserved As Long, _ 
              ByVal lpfnCB As Long) As Long 


`enter code here`Sub DownloadFileFromWeb() 
Dim i As Integer 

    Const strUrl As String = "https://test.com/sites/Field Completions Reported " & Range("B1") & ".xlsb" 
    '"https://test.com/sites/Field Completions Reported 01 04 2016.xlsb" 

    Dim strSavePath As String 
    Dim returnValue As Long 

    strSavePath = "C:\Users\1234\Desktop\Field Completions Reported.xlsb" 
    returnValue = URLDownloadToFile(0, strUrl, strSavePath, 0, 0) 

End Sub 

}

+0

'CONST strUrl作爲字符串= 「https://test.com/sites/Field達成報道」 &範圍( 「B1」)「 .xlsb「'。正如編譯器所說,不斷需要,'Range()'不允許 – Rosetta

+0

考慮將它調暗爲字符串。那麼你可以使用'range()'來分配它 – Rosetta

+0

請參閱[SaveAs不會在Excel VBA中包含「。」的字符串](http://stackoverflow.com/questions/36320580/saveas-wont-accpet-字符串,包含在excel-vba/36320966#36320966)關於從範圍saveas和日期。 – Jeeped

回答

2

Compile error: Constant expression required

你不能用Variable使用Const。當你使用Const然後傳遞一些不會改變的東西。例如

Const a = "Sid" '<~~~ This will work 
Const a = "Sid" & i '<~~ This will not work. i is a variable 
Const a = "Sid" & Range("A1").Value '<~~ This will not work. Range("A1") is a variable 

您的代碼更改此

Dim strUrl As String 

'"https://test.com/sites/Field Completions Reported 01 04 2016.xlsb" 
strUrl = "https://test.com/sites/Field Completions Reported " & _ 
     Range("B1").Value & ".xlsb" 
+0

您的傳奇......非常感謝您! –

+0

我剛剛意識到@KSSheon已經在上面的評論中提出了這個建議。請不要接受這個答案。讓他回答這個問題,然後你可以接受他的回答:) –