【问题标题】:VBA Open any workbookVBA 打开任何工作簿
【发布时间】:2013-10-13 04:25:30
【问题描述】:

我有一个宏,它可以从特定文件夹打开电子表格,并将输出保存到另一个工作簿中名为 Sheet1 的工作表中。如果文件名被称为“MyFile.xls”,宏就可以工作,但我希望它能够在任何文件名上运行,但它必须有一个“Book2”工作表。

这是我的代码:

Dim source As Workbook
Dim output As Workbook
Dim sourceSheet as WorkSheet
Dim outputSheet as WorkSheet
Dim file As String
file = "C:\Spreadsheets\MyFile.xls"  'I would like it to handle any files from any location'

Set output = ThisWorkBook
output.Activate

If Len(Dir$(file)) > 0 Then
    Set source = workbooks.Open(file)

Set sourceSheet = source.Worksheets("Book2") 'Must only run if the sheet is called Book2'
Set outputSheet = output.Worksheets("Sheet1") 'Saves sheets into a new sheet called Sheet1'

End Sub

【问题讨论】:

  • 你的意思是如果没有名为“Book2”的工作表就不应该运行吗?
  • 是的,如果没有名为 Book2 的工作表则不应运行,但它可以打开任何 excel 文件,而不仅仅是 MyFile.xls
  • 我发现了一个错误。我测试了代码并修改了我的帖子。请刷新页面以查看更新的答案。
  • 我看到你没有接受这个答案。代码遇到一些困难?

标签: vba excel


【解决方案1】:

这是你正在尝试的吗? (经过试验和测试)

Sub Sample()
    Dim source As Workbook, output As Workbook
    Dim sourceSheet As Worksheet, outputSheet As Worksheet

    Dim File

    '~~> Show a dialog to open any excel file
    File = Application.GetOpenFilename("Excel Files (*.xls*), *.xls*")

    If File = False Then Exit Sub

    Set output = ThisWorkbook

    If Len(Dir$(File)) > 0 Then
        Set source = Workbooks.Open(File)

        '~~> Error check to see if the workbook has that sheet
        On Error Resume Next
        Set sourceSheet = source.Worksheets("Book2")

        If Err.Number = 0 Then

            Set outputSheet = output.Worksheets("Sheet1")
            '
            '~~> Rest of your code
            '
        Else
            MsgBox "Not found"
            source.Close SaveChanges:=False
        End If
        On Error GoTo 0
    End If
End Sub

【讨论】:

  • 这似乎对我不起作用。它没有正确读取文件
  • It doesn't read the file correctly你能再解释一下吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-16
  • 1970-01-01
相关资源
最近更新 更多