VBA:从服务器获取/下载Excel文件并将内容复制到新工作表中

时间:2012-12-20 13:46:08

标签: excel vba copy worksheet

由于某种原因,以下宏不起作用:

Sub ExtractDataTest()


    Dim FilePath$, Row&, Column&, Address$


 'change constants & FilePath below to suit
     '***************************************
    Const FileName$ = "Dxo.xlsx"
    Const SheetName$ = "Open"
    Const NumRows& = 50
    Const NumColumns& = 20
    FilePath = ("http://enhanced1.sharepoint.hx.com/teams/")
     '***************************************


    DoEvents
    Application.ScreenUpdating = False
        If Dir(FilePath & FileName) = Empty Then
        MsgBox "The file " & FileName & " was not found", , "File Doesn't Exist"
        Exit Sub
    End If
    For Row = 1 To NumRows
        For Column = 1 To NumColumns
            Address = Cells(Row, Column).Address
            Cells(Row, Column) = GetData(FilePath, FileName, SheetName, Address)
            Columns.AutoFit
        Next Column
    Next Row
    ActiveWindow.DisplayZeros = False
End Sub




Private Function GetData(Path, File, Sheet, Address)
    Dim Data$
    Data = "'" & Path & "[" & File & "]" & Sheet & "'!" & _
    Range(Address).Range("A1").Address(, , xlR1C1)
    GetData = ExecuteExcel4Macro(Data)
End Function

我在线上遇到运行时错误'52'(“错误的文件名或号码”):

If Dir(FilePath & FileName) = Empty Then

有趣的是它确实有效。当位置为'C:\'时,它可以工作,我不会收到错误。奇怪的东西。

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

从文件系统打开文件与通过HTTP下载文件完全不同。 最简单的不可知方法是简单地使用允许HTTP URI的Workbooks.Open;

Set wb = Workbooks.Open(FilePath & FileName)

(您只需删除Dir()作为文件系统的内容)