【发布时间】:2018-11-07 18:07:15
【问题描述】:
我有多个报告需要按照特定步骤编译成一个主文件,然后在新数据的左侧添加一个日期。需要遵循的步骤是:
- 在目录中打开一个文件
- 根据文件名设置一个变量,以便在后面的步骤中使用(我为此使用了 InputBox 函数)
- 从该文件复制所有包含 A 列数据的单元格
- 将单元格数据粘贴到我的主文件 B 列的第一个空白单元格中
- 如果 B 列中有数据,并且 A 列中的相邻单元格为空白,则将该单元格的值更改为步骤 2 中选择的变量
- 关闭文件并打开目录中的下一个文件
所以基本上,它需要打开文件 X,将文件 X 的 A 列中的所有内容复制到主文件的 B 列,然后在主文件的 B 列中为 B 列中有数据的每一行插入一个日期
我被困在第 5 步,无法找到一种方法来找到从第 4 步中粘贴了数据的所有单元格,并将所有单元格的值直接设置到它们的左侧。
Option Explicit
Sub ImportGroups()
Dim fPATH As String, fNAME As String
Dim LR As Long, NR As Long
Dim wbGRP As Workbook, wsDEST As Worksheet
Dim dateChooser As Variant
Dim cell As Range
Set wsDEST = ActiveWorkbook.Sheets("Sheet1")
Application.DisplayAlerts = False
fPATH = "C:\<path>\" 'remember the final \ in this string
fNAME = Dir(fPATH & "*") 'get the first filename in fpath
Do While Len(fNAME) > 0
Set wbGRP = Workbooks.Open(fPATH & fNAME) 'open the file
LR = Range("A" & Rows.Count).End(xlUp).Row 'how many rows of info?
If LR > 3 Then
dateChooser = InputBox("Enter date based on this file name: " & fNAME)
ActiveSheet.Range("A1:A" & LR).Copy
wsDEST.Cells(Rows.Count, 2).End(xlUp).Offset(1, 0).PasteSpecial xlPasteValue
' This is where I need to set the value of all cells adjacent to the pasted cells
End If
wbGRP.Close False 'close data workbook
fNAME = Dir 'get the next filename
Loop
Application.DisplayAlerts = True
End Sub
【问题讨论】:
-
当您跨多个工作簿工作时,使用工作簿/工作表正确限定您的对象非常重要。你有不合格的
ActiveSheet的范围和实例,应该被删除 -
为
Option Explicit点赞 -
我相信
Range("A" & LastRow + 1 & "A" & LastRow + LR)是您要查找的范围(其中LastRow 是A的wsDEST列中最后一个填充单元格)