【问题标题】:Opening .XLSX files and copying/pasting data打开 .XLSX 文件并复制/粘贴数据
【发布时间】:2018-10-06 01:41:48
【问题描述】:

我正在尝试创建一个循环遍历文件夹中所有非 txt 文件的宏,打开它们,从打开的文件中复制选择,然后将其粘贴到带有宏的文件中的特定工作表(取决于正在复制哪个文件)。我已经让前两个部分工作,但我无法让复制部分工作。它不断复制应该是粘贴文件的文件。知道我做错了什么吗?

Private Sub CommandButton1_Click()

Dim Path As String
Dim File As String
Dim PasteFile As String
Dim Month As String
Dim FY As String

Month = "feb"
FY = "18"
PasteFile = ThisWorkbook.Name

Application.ScreenUpdating = False
Application.EnableEvents = False
Application.Calculation = xlCalculationManual

Path = "[file path]"
file = Dir(Path)
Do While file <> "*.txt" Or file <> ""

    If file = "[file name]" & Month & FY & ".xlsx" Then
    Workbooks.Open Path & file
    Workbooks(file).Worksheets("Sheet1").Activate
    Range(Cells(1, 1), Cells(5, 5)).Copy
    Workbooks(myFile).Worksheets("Sheet1").Activate
    Cells(10, 3).PasteSpecial xlPasteValues

    End If
File = Dir()
Loop
End Sub

【问题讨论】:

标签: vba excel


【解决方案1】:

避免使用.Activate.Select

How to Avoid the Select Method in VBA & Why

Private Sub CommandButton1_Click()

Dim Path As String
Dim File As String
Dim PasteFile As String
Dim Month As String
Dim FY As String

Month = "feb"
FY = "18"
PasteFile = ThisWorkbook.Name

Application.ScreenUpdating = False
Application.EnableEvents = False
Application.Calculation = xlCalculationManual

Path = "[file path]"
File = Dir(Path)
Do While File <> "*.txt" Or File <> ""

    If File = "[file name]" & Month & FY & ".xlsx" Then

    Workbooks.Open Path & File

    With Workbooks(File).Worksheets("Sheet1")
    .Range(.Cells(1, 1), .Cells(5, 5)).Copy
    End With

    With Workbooks(myFile).Worksheets("Sheet1")
    .Cells(10, 3).PasteSpecial xlPasteValues
    End With

    End If

File = Dir()
Loop

End Sub

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-04-24
    • 1970-01-01
    • 2023-01-19
    • 1970-01-01
    • 2016-04-03
    • 2017-10-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多