【问题标题】:VBA unable to read files after closing and reopen excel关闭并重新打开excel后VBA无法读取文件
【发布时间】:2019-08-07 14:20:27
【问题描述】:

假设我在同一个文件夹中有 3 个文件(item.xlsx、master.xlsx、transfer.xlsm) 主要目的是将数据从项目传输到主文件。

我在 transfer.xlsm 中编写所有代码,并允许用户输入文件名和列映射。我已经为代码做了几个小时并且已经测试了几次并且工作得很好。只需单击一个按钮,就可以从 item.xlsx 读取数据并根据列映射复制到 master.xlsx。

但是当我关闭所有 3 个文件并重新打开时出现问题。我打开所有 3 个文件,当我单击传输按钮时,xlsm 它显示未找到文件,这是我所做的错误处理。我确实尝试在我的桌面上创建一个新文件夹并在其中创建一个全新的 transfer.xlsm,我将项目和主文件复制过来,并将我的代码复制到我的新按钮中。它实际上可以工作,但是当我关闭并在该新文件夹中重新打开时不起作用,

当我处理它时基本上工作正常,当我完全关闭它并重新打开它时无法检测到这两个文件。

根据用户输入在 transfer.xlsm 中输入单元格值

source = Cells(5, 2)
sourceSheet = Cells(6, 2)
sourceSheetRow = Cells(7, 2) - 1

destination = Cells(8, 2)
destinationSheet = Cells(9, 2)
destinationSheetRow = Cells(10, 2) - 1

source = source + ".xlsx"
destination = destination + ".xlsx"

rows = Cells(11, 2)

If FileExists(source) = False Or FileExists(destination) = False Then
    MsgBox "File not found, please double check file name and make sure is in the same folder"
Exit Sub
End If

For i = 1 To rows
...
Next i

Function FileExists(FilePath As String) As Boolean
Dim TestStr As String
    TestStr = ""
    On Error Resume Next
    TestStr = Dir(FilePath)
    On Error GoTo 0
    If TestStr = "" Then
        FileExists = False
    Else
        FileExists = True
    End If
End Function

我创建了这个 transfer.xlsm,以便我可以将它发送给人们,如果他们想将数据块从一个 excel 复制到另一个而不是逐行复制粘贴。希望有人能给我一些指导

【问题讨论】:

  • 可以添加单元格值的截图吗?

标签: excel vba file-not-found


【解决方案1】:

根据您提供的信息,我假设用户提供的信息只是没有扩展名的文件名:itemmaster,而不是完整的文件路径C:\SampleFolder\item.xlsxC:\SampleFolder\master.xlsx .此外,我假设当您运行此代码时,所有三个文件都必须位于同一文件夹中。

如果是这种情况,请尝试使用ThisWorkbook.Path,您可以将其应用到您的源路径和目标路径,以确保使用了适当的文件路径。

Dim sPath as String
sPath = ThisWorkbook.Path + "\"

source = Cells(5, 2)
sourceSheet = Cells(6, 2)
sourceSheetRow = Cells(7, 2) - 1

destination = Cells(8, 2)
destinationSheet = Cells(9, 2)
destinationSheetRow = Cells(10, 2) - 1

source = source + ".xlsx"
destination = destination + ".xlsx"

If FileExists(sPath + source) = False Or FileExists(sPath + destination) = False Then
    MsgBox "File not found, please double check file name and make sure is in the same folder"
Exit Sub
End If
...

【讨论】:

  • 非常感谢,这解决了它,但又出现了另一个问题。现在能够检测到文件存在,但在传输发生时它给了我错误。我的代码如下: Workbooks(destination).Worksheets(destinationSheet).Cells(destinationSheetRow + i, Cells(8, j + 3)) _ = Workbooks(source).Worksheets(sourceSheet).Cells(sourceSheetRow + i, Cells(4 , j + 3)) 在调试模式下,源值和目标值是正确的完整路径但无法运行。
  • 那是因为我们将sourcedestination设置为完整的文件路径。 Workbook(index) 只能识别文件名(即Workbook("filename.xlsx"),而不能将Workbook("C:\SampleFolder\filename.xlsx") 识别为有效的工作簿。为了您的目的,我已经相应地更新了我的解决方案。
猜你喜欢
  • 2019-07-03
  • 1970-01-01
  • 1970-01-01
  • 2014-12-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-06
  • 1970-01-01
相关资源
最近更新 更多