将数据从一个Excel工作簿复制到另一个工作簿

时间:2016-02-05 16:54:28

标签: excel-vba vba excel

我正在尝试编写一个代码,该代码使用单击按钮来抓取输入工作簿中的数据,然后将其粘贴到我的输出工作簿中。我无法弄清楚的问题是我的输入工作簿名称按日期更改,但它们都在相同的命名约定中。我希望代码拉出最新的日期输入文件,然后将其粘贴到输出工作簿中。我不知道从哪里开始......任何帮助都是值得欣赏的。

谢谢

1 个答案:

答案 0 :(得分:2)

我同意肯:你在一个问题上要求太多。此外,“从我的输入工作簿中抓取数据然后将其粘贴到我的输出工作簿中”可能意味着什么。但是,这是我用来解决您需求的第一部分的功能。参数是文件夹名称和文件模板。它返回与模板匹配的文件夹中最新文件的名称。

Function NewestFileName(ByVal Path As String, ByVal FileTemplate As String) As String

  ' * Finds, and returns the name of, the newest file in folder Path with a name
  '   that matches FileTemplate.  Returns "" if no matching file is found.

  ' * Path          Folder in which to search for files
  ' * FileTemplate  File name specification of the file required.  For example:
  '                     MyFile*.xls

  ' 25Jul11  Copied from RiskRegisterControl V43.xls.
  ' 22Nov11  Name changed from NewestFile to NewestFileName to match NextFileName.
  ' 20Apr12  Minor improvements

  Dim FileDateCrnt              As Date
  Dim FileDateNewest            As Date
  Dim FileNameCrnt              As String
  Dim FileNameNewest            As String

  If Right(Path, 1) <> "\" Then
    Path = Path & "\"
  End If

  FileNameCrnt = Dir$(Path & FileTemplate)
  If FileNameCrnt = "" Then
    NewestFileName = ""
    Exit Function
  End If

  FileNameNewest = FileNameCrnt
  FileDateNewest = FileDateTime(Path & FileNameCrnt)
  Do While True
    FileNameCrnt = Dir$
    If FileNameCrnt = "" Then Exit Do
    FileDateCrnt = FileDateTime(Path & FileNameCrnt)
    If FileDateCrnt > FileDateNewest Then
      FileNameNewest = FileNameCrnt
      FileDateNewest = FileDateCrnt
    End If
  Loop

  NewestFileName = FileNameNewest

End Function