简体   繁体   English

文件夹选择对话框(VBA,Excel 2010)导致文件不可读

[英]Folder Selection Dialog Box (VBA, Excel 2010) causing files to be unreadable

This may be quite a lengthy description, so please bear with me. 这可能是一个冗长的描述,所以请耐心等待。 The problems I am experiencing with Excel are related to custom macros, VBA, and file access. 我在Excel中遇到的问题与自定义宏,VBA和文件访问有关。

Background : I am trying to write a macro to process multiple CSV workbooks of data. 背景 :我正在尝试编写一个宏来处理数据的多个CSV工作簿。 I have files named RawData_1.csv until RawData_x.csv where x is the number of files I have in a particular folder. 我有一个名为RawData_1.csv的文件,直到RawData_x.csv,其中x是我在特定文件夹中拥有的文件数。

My code for the macro looks like this: 我的宏代码如下所示:

Sub ImportData()

    Application.ScreenUpdating = False

    Dim strDir As String
    Dim strFileName As String
    Dim wbToCopy As Workbook
    Dim intCol As Integer

    Set master = ActiveSheet

    **PLEASE SEE BELOW FOR 2 VERSIONS OF CODE THAT CAN GO HERE!**

    strFileName = Dir(strDir & "\*.csv")

    intCol = 2

    Do While Len(strFileName) > 0
        Set wbToCopy = Workbooks.Open(strFileName, , True)

        //Do other things I need it to do here

        wbToCopy.Close (False)

        strFileName = Dir
        intCol = intCol + 2
    Loop

    Application.ScreenUpdating = True

End Sub

Problem 1 (tiny problem) : When I execute the macro, the files somehow "change," and the next time I execute the same macro in the same folder, it will report that the files are not found. 问题1(微小问题) :当我执行宏时,文件以某种方式“更改”,而下次我在同一文件夹中执行相同的宏时,它将报告未找到文件。 The exact error is: 确切的错误是:

Run-time error '1004': 运行时错误“ 1004”:

'RawData_1.csv' could not be found. 找不到“ RawData_1.csv”。 Check the spelling of the file name, and verify that the file location is correct. 检查文件名的拼写,并验证文件位置是否正确。

If you are trying to open the file from your list of most recently used files, make sure that the file has now been renamed, moved, or deleted. 如果要尝试从最近使用过的文件列表中打开文件,请确保已重命名,移动或删除了该文件。

I have figured out a solution to this problem. 我已经找到了解决这个问题的方法。 All I have to do is go into the folder with all the csv files, open the FIRST one in the list, and "Save As" as a MS-DOS CSV file. 我所要做的就是进入包含所有csv文件的文件夹,打开列表中的第一个文件,然后将“另存为”另存为MS-DOS CSV文件。 Once I have done this, I can run the macro and it will be able to open ALL the files (not just the first file that I "save as"-ed). 完成此操作后,我可以运行宏,它将能够打开所有文件(而不仅仅是我“另存为” -ed的第一个文件)。

While this is annoying, it's not the worst thing in the world. 尽管这很烦人,但这并不是世界上最糟糕的事情。 If there is a reason why excel is doing this, I would love to know! 如果有某个原因让excel做到这一点,我很想知道! If there is a solution to this problem, even better! 如果有解决此问题的方法,那就更好了!

Problem 2 (Big problem) This is the main puzzle that I would like to solve. 问题2(大问题)这是我要解决的主要难题。 In the code above, the section that is missing is the part of the code that tells Excel (or the macro) where to find the files. 在上面的代码中,缺少的部分是告诉Excel(或宏)在哪里找到文件的代码部分。 I can do this by hardcoding in the path as follows: 我可以通过如下方式对路径进行硬编码来做到这一点:

Method 1: 方法1:

strDir = "C:\whateverPath"

This method ALWAYS works (except when Problem 1 is encountered above). 此方法始终有效(上面遇到问题1时除外)。

However, this is clearly not the best way to write the macro, since I will not only be using it once, but will need to use it multiple times, and the data files I wish to import will be in various folders. 但是,这显然不是编写宏的最佳方法,因为我不仅会使用一次,而且需要多次使用,而且我希望导入的数据文件将位于各个文件夹中。 Therefore, I tried to write it as follows: 因此,我尝试将其编写如下:

Method 2: 方法2:

Dim folderDialog As fileDialog 
Set folderDialog = Application.FileDialog(msoFileDialogeFolderPicker)
folderDialog.AllowMultiSelect = False
folderDialog.Show

strDir = folderDialog.SelectedItems(1)

I compared strDir from Method 1 and strDir from Method 2 and found no discernable differences in their values. 我比较了方法1的strDir和方法2的strDir,发现它们的值没有明显区别。 They both contain the correct path "C:\\whateverPath". 它们都包含正确的路径“ C:\\ whateverPath”。

However, using Method 2, excel will be unable to read any of the files in the selected folder. 但是,使用方法2,excel将无法读取所选文件夹中的任何文件。 It will return with The same run-time error 1004 as above, and the quick fix I found for Problem 1 above does nothing to help the macro run. 它将返回与上面相同的运行时错误1004,并且我为上面的问题1找到的快速修复无法帮助宏运行。

If anyone has any idea what is going on here, I would really appreciate some help figuring this out! 如果有人对这里发生的事情有任何了解,我将非常感谢您提供帮助以解决此问题!

Edit: I think I found the issue. 编辑:我想我找到了问题。 Set wbToCopy = Workbooks.Open(strFileName, , True) , strFileName does not use the fully qualified path. Set wbToCopy = Workbooks.Open(strFileName, , True)strFileName不使用完全限定的路径。 So when you call the .open method, I believe VBA is using the CurDir value and appending it to strFileName . 因此,当您调用.open方法时,我相信VBA正在使用CurDir值并将其附加到strFileName When you perform your "Save As", the CurDir value is changed to the directory you are saving the .csv files in. This gives the illusion that the "Save As" action is what allows your macro to run. 当您执行“另存为”时, CurDir值将更改为要保存.csv文件的目录。这给人一种幻想,即“另存为”操作可以使您的宏运行。 In actuality, it is the act of changing the CurDir value to the directory where the files are located. 实际上,这是将CurDir值更改为文件所在目录的行为。 Use a fully qualified file name with .open and it should run everytime. 将完全限定的文件名与.open一起.open ,它应该每次都运行。

Previous Suggestion: I don't think your file name is full qualified (your error message should read 'C:\\whateverPath\\RawData_1.csv' could not be found. not 'RawData_1.csv' could not be found. ). 先前的建议:我认为您的文件名不是完全限定的(您的错误消息应显示为'C:\\whateverPath\\RawData_1.csv' could not be found.找不到'RawData_1.csv' could not be found. )。

I was having a tough time tracking down the error in the code. 我很难追踪代码中的错误。 This is kind of hacked together but if you get stuck, try using this: 这有点被黑,但是如果您卡住了,请尝试使用以下方法:

Option Explicit
Sub ImportData()

Application.ScreenUpdating = False

Dim strDir As String
Dim strFolderName As String
Dim wbToCopy As Workbook
Dim intCol As Integer
Dim master As Excel.Worksheet

Dim FSO As Object
Dim FSO_FOLDER As Object
Dim FSO_FILE As Object
Dim FILE_EXT As String

FILE_EXT = "csv"
strFolderName = Get_Folder_Path() & "\"

''Create FileSystem Objects
Set FSO = CreateObject("Scripting.FileSystemObject")

Set FSO_FOLDER = FSO.GetFolder(strFolderName)

Set master = ThisWorkbook.ActiveSheet

''**PLEASE SEE BELOW FOR 2 VERSIONS OF CODE THAT CAN GO HERE!**

intCol = 2

If FSO_FOLDER.Files.Count > 0 Then

''Loop through each File in Folder
For Each FSO_FILE In FSO_FOLDER.Files

   ''Test extension
   If FSO.GetExtensionName(FSO_FILE.Name) = FILE_EXT Then

       Set wbToCopy = Workbooks.Open(strFolderName & FSO_FILE.Name, , True)

        ''//Do other things I need it to do here

        wbToCopy.Close (False)
        intCol = intCol + 2

   Else: End If

Next

Else

MsgBox "No Files Found at " & strFolderName

End If

Set FSO = Nothing
Set FSO_FOLDER = Nothing

Application.ScreenUpdating = True

End Sub

Function Get_Folder_Path() As String
Dim folderDialog As FileDialog
Set folderDialog = Application.FileDialog(4)
folderDialog.AllowMultiSelect = False
folderDialog.Show

Get_Folder_Path = folderDialog.SelectedItems(1)

End Function

Note that this uses the FileSystem library instead of the native Dir function. 请注意,这使用FileSystem库而不是本机Dir函数。 You also will select the folder name instead of a file name for the dialog box. 您还将为对话框选择文件夹名称而不是文件名称。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM