2014-03-05 19 views
2

所以情況就是這樣:我試圖從外部服務器下載一些圖片到我的本地計算機上。什麼是自動從Excel/VBA中的鏈接下載圖片的方法?

Excel文件有一個鏈接,這將打開並下載畫中畫。

我到目前爲止已經試過是超鏈接轉換成只是文本(圖片URL)和運行下面的代碼。

我只有基本熟悉VBA,更何況與其他語言雖然。這裏是我的代碼至今:

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 

    Dim Ret As Long 

    '~~> This is where the images will be saved. Change as applicable 
    Const FolderName As String = "C:\Users\My Name\Downloads\" 

    Sub DownloadLinks() 
Dim ws As Worksheet 
Dim LastRow As Long, i As Long 
Dim strPath As String 

'~~> Name of the sheet which has the list 
Set ws = Sheets("Sheet1") 

LastRow = ws.Range("B" & Rows.Count).End(xlUp).Row 

    For i = 2 To LastRow '<~~ 2 because row 1 has headers 
    strPath = FolderName & ws.Range("BP" & i).Value & ".jpg" 

    Ret = URLDownloadToFile(0, ws.Range("BP" & i).Value, strPath, 0, 0) 

    If Ret = 0 Then 
     ws.Range("CA" & i).Value = "File successfully downloaded" 
    Else 
     ws.Range("CA" & i).Value = "Unable to download the file" 
    End If 
Next i 

    End Sub 

列名是無關緊要的,但現在,一切都出來爲「無法下載文件」,或者如果它是成功的,它是不是在我的目錄指定。

有沒有更好的方法來編碼?

有關我的數據可能嗎?

我也想它如果可能的文件名中的另一列保存爲文本,但是這是沒有必要的。

現在我只需要他們下載。

+0

看起來你正在使用的列BP的URL和文件名都 - 是正確的? –

+0

我很想知道,因爲鏈接導入到excel的方式,只是文件名是超鏈接的文本,認爲完整的地址是可用的超鏈接。這將是完美的,因爲它應該將保存的文件命名爲文件名,而不是整個超鏈接,但它沒有做任何事情。 –

+0

使用單元格的值來命名文件沒有問題,但是您需要將實際的URL傳遞給下載函數,這是單元格的「超鏈接」屬性的屬性,而不是單元格的值。 –

回答

2

試試這個:

Sub DownloadLinks() 
Dim ws As Worksheet 
Dim LastRow As Long, i As Long 
Dim strPath As String, strURL As String 
Dim c As Range 


    Set ws = Sheets("Sheet1") 

    LastRow = ws.Range("B" & Rows.Count).End(xlUp).Row 

    For i = 2 To LastRow 

     Set c = ws.Range("BP" & i) 
     If c.Hyperlinks.Count>0 Then 
      strPath = FolderName & c.Value & ".jpg" 
      strURL = c.Hyperlinks(1).Address 

      Ret = URLDownloadToFile(0, strURL, strPath, 0, 0) 

      ws.Range("CA" & i).Value = IIf(Ret = 0, _ 
            "File successfully downloaded", _ 
            "Unable to download the file") 
     Else 
      ws.Range("CA" & i).Value = "No hyperlink!" 
     End If 
    Next i 

End Sub 
+0

我試過了,但'strURL = c.Hyperlinks(1).Address'出錯了,「下標超出範圍。」這是否有字符限制?這些網址很長! –

+0

嘗試在該行上方添加'debug.print cell.hyperlinks.count',看看輸出是什麼。你的鏈接是實際的超鏈接,還是你使用'HYPERLINK()'公式? –

+0

他們是真正的超鏈接。 –

相關問題