【发布时间】:2019-05-10 09:30:27
【问题描述】:
我的代码将遍历文件夹中的所有文件,并将信息从工作表“管理器表单”复制到选定的单元格到主文件。 当我想添加更多要复制的范围时,它会阻止我出错。
问题在于这一行:
NewSht.Range("B" & PasteRow).PasteSpecial xlPasteValues
我应该如何指定要粘贴的范围?
Dim folderPath As String
Dim Filename As String
Dim wb As Workbook
Dim Masterwb As Workbook
Dim sh As Worksheet
Dim NewSht As Worksheet
Dim OldSht As Worksheet
Dim FindRng As Range
Dim PasteRow As Long
' set master workbook
Set Masterwb = Workbooks("result2.xlsm")
folderPath = "C:\Users\Downloads\Tech\TimeSheets2019\inside" 'contains folder path
If Right(folderPath, 1) <> "\" Then folderPath = folderPath & "\"
Application.ScreenUpdating = False
Filename = Dir(folderPath & "*.xlsx*")
Do While Filename <> ""
Set wb = Workbooks.Open(folderPath & Filename, ReadOnly:=True)
Set NewSht = Masterwb.Worksheets("Tabelle1") ' added
Set OldSht = wb.Worksheets("Manager Form") ' added
' get the first empty row in the new sheet
Set FindRng = NewSht.Cells.Find(What:="*", Lookat:=xlPart, LookIn:=xlFormulas, SearchOrder:=xlByRows, SearchDirection:=xlPrevious, MatchCase:=False)
If Not FindRng Is Nothing Then ' If find is successful
PasteRow = FindRng.Row + 1
Else ' find was unsuccessfull > new empty sheet, should paste at the first row
PasteRow = 1
End If
OldSht.Range("B7").Copy
NewSht.Range("B" & PasteRow).PasteSpecial xlPasteValues
wb.Close False
【问题讨论】:
-
出错时
PasteRow的值是多少? -
PasteRow 应该是第一个空行,在这种情况下它是 NewSht 中的第二行
-
如果您只是粘贴值,为什么不使用
Range(y).Value = Range(x).Value?它会明显更快。 -
你说是2还是应该是2?
-
我的代码应该从每个文件中复制 5 个范围,并在 NewSht 的第一个空闲行中一个接一个地复制它。它将包含姓名、时间、日期等。目前第一个空行是第二行,但没有粘贴任何内容。