将电子表格从“下载”文件夹本地复制到不同电子表格的主工作表中

时间:2018-01-31 23:28:33

标签: excel vba excel-vba download

我遇到了障碍,我无法理解我的生活。以下是我要完成的任务:

  • 我使用的程序会将数据快照导出到电子表格(.xls)到本地的下载文件夹中。
  • 我需要将此电子表格的sheet1数据(不打开)复制到我保存在其他地方的主电子表格中,这是“主要”表格并且打开 。我在主表上有一个运行此代码的宏按钮。

需要注意的是,我必须使“下载”文件夹动态,因为它不是特定的用户名,因为它将被多个用户使用。

此代码适用于1个人:

Sub sbCopyingAFile()
Dim MyFile As String, Str As String, MyDir As String, Wb As Workbook
Dim Rws As Long, Rng As Range
Set Wb = ThisWorkbook
MyDir = "C:\Users\{My_Username}\Downloads\"
MyFile = Dir(MyDir & "*.xls")
ChDir MyDir
Application.ScreenUpdating = 0
Application.DisplayAlerts = 0

Do While MyFile <> ""
    Workbooks.Open (MyFile)
    With Worksheets(1)
        Rws = .Cells(Rows.Count, "A").End(xlUp).Row
        Set Rng = Range(.Cells(2, 1), .Cells(Rws, 19))
        Rng.Copy Wb.Worksheets("DUMP").Cells(Rows.Count, "B").End(xlUp).Offset(0, 0)
        ActiveWorkbook.Close True
    End With
    MyFile = Dir()
Loop
On Error Resume Next
    Kill "C:\Users\{My_Username}\Downloads\*.*"
On Error GoTo 0

End Sub

这是我最后一次尝试获取任何下载文件夹,而不是特定于用户名:

Sub sbCopyingAFile()
Dim MyFile As String, Str As String, Wb As Workbook, MyDir As String
'Dim fso
Dim Rws As Long, Rng As Range
'Set fso = CreateObject("Scripting.FileSystemObject")
Set Wb = ThisWorkbook
MyDir = CreateObject("WScript.Shell").specialfolders("Downloads")
'MyDir = "C:\Users\{My_Username}\Downloads\"
MyFile = Dir(MyDir & "*.xls")
ChDir MyDir
Application.ScreenUpdating = 0
Application.DisplayAlerts = 0

Do While MyFile <> ""
Workbooks.Open (MyFile)
With Worksheets(1)
    Rws = .Cells(Rows.Count, "A").End(xlUp).Row
    Set Rng = Range(.Cells(2, 1), .Cells(Rws, 19))
    Rng.Copy Wb.Worksheets("DUMP").Cells(Rows.Count, "B").End(xlUp).Offset(0, 0)
    ActiveWorkbook.Close True
End With
MyFile = Dir()
Loop
On Error Resume Next
'Kill "C:\Users\{My_Username}\Downloads\*.*"
On Error GoTo 0
End Sub

2 个答案:

答案 0 :(得分:1)

您可以使用Environ$("Username")获取当前用户名。这将返回一个字符串。

所以你的道路看起来像是:

"C:\Users\" & Environ$("Username") & "\Downloads\"

答案 1 :(得分:1)

如果用户在非Environ$("UserProfile") & "\Downloads\"

的奇怪地方设置个人资料,您也可以使用"C:\Users"