Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/excel/26.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
关闭并重新打开excel后,VBA无法读取文件_Excel_Vba_File Not Found - Fatal编程技术网

关闭并重新打开excel后,VBA无法读取文件

关闭并重新打开excel后,VBA无法读取文件,excel,vba,file-not-found,Excel,Vba,File Not Found,假设我有3个文件都在同一个文件夹中(item.xlsx、master.xlsx、transfer.xlsm),主要目的是将数据从item传输到master 我执行transfer.xlsm中的所有代码,并允许用户输入文件名和列映射。我已经做了几个小时的代码和测试了好几次,是完美的工作。只需单击一个按钮,即可从item.xlsx读取数据,并根据列映射复制到master.xlsx 然而,当我关闭所有3个文件并再次打开时,问题就出现了。我打开所有3个文件,当我点击传输按钮时,xlsm显示文件未找到,这

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

我执行transfer.xlsm中的所有代码,并允许用户输入文件名和列映射。我已经做了几个小时的代码和测试了好几次,是完美的工作。只需单击一个按钮,即可从item.xlsx读取数据,并根据列映射复制到master.xlsx

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

基本上是工作正常,当我在它的工作,当我关闭它完全重新打开它是无法检测到2个文件

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


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

基于您提供的信息,我假设用户提供的信息只是文件名,没有扩展名:
item
master
,而不是完整的文件路径
C:\SampleFolder\item.xlsx
C:\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
...

你能添加单元格值的屏幕截图吗?非常感谢,这解决了它,但它会出现另一个问题。现在可以检测文件是否存在,但在传输发生时会出现错误。下面是我的代码:工作簿(目标).工作表(目标表).单元格(目标表Row+i,单元格(8,j+3))\uU9=工作簿(源).工作表(源表).调试模式下的单元格(源表Row+i,单元格(4,j+3)),源和目标值是正确的完整路径,但无法运行。这是因为我们将
source
destination
设置为完整文件路径<代码>工作簿(索引)仅识别文件名(即
工作簿(“filename.xlsx”
),而不识别
工作簿(“C:\SampleFolder\filename.xlsx”)
为有效工作簿。我已根据您的需要相应更新了解决方案。
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
...