【发布时间】:2016-07-06 08:48:58
【问题描述】:
我使用了在此处找到的一些代码开始尝试将大量 Excel CSV 文件转换为 Excel 2003 格式。在转换过程中,我想打开一个默认位置文件夹,然后导航到 CSV 文件所在的正确子文件夹,但是在单步执行代码时,我的变量之一不会填充。我的代码在下面,不会填充的变量是 strDir。
我想要用默认位置 + 我选择的文件夹填充 strDir 的代码,但是我不确定我需要对这段代码执行什么操作以使其能够做到这一点。
现在我只有硬编码的默认位置,当代码运行时,这个位置会打开。但是,当我选择子文件夹时,如何以编程方式记录?
我知道我想做什么,但如何在 VBA 中实现这一点是我的问题。
Public Sub CSV_to_XLS()
Dim wb As Workbook
Dim strFile As String
Dim strDir As String
Dim strDirCapture As String
'Set base directory for get folder to manipulate csv files
strDirCapture = GetFolder("\\DEVP-APPS-07\File Storgae\1_Pending\")
'strDir = strDirCapture
strDir = strDirCapture & "\"
strFile = Dir(strDir & "*.csv")
MsgBox "String directory path = " & strDirCapture
MsgBox "StrFile = " & strFile
Do While strFile <> ""
'Set wb = Workbooks.Open(Filename:=strDir & strFile, Local:=True)
'wb.SaveAs Replace(wb.FullName, ".csv", ".xls"), 56 'UPDATE:
wb.Close True
Set wb = Nothing
strFile = Dir
Loop
End Sub
Function GetFolder(strPath As String) As String
Dim fldr As FileDialog
Dim sItem As String
Set fldr = Application.FileDialog(msoFileDialogFolderPicker)
With fldr
.Title = "Select a Folder"
.AllowMultiSelect = False
.InitialFileName = strPath
If .Show <> -1 Then GoTo NextCode
sItem = .SelectedItems(1)
End With
NextCode:
GetFolder = sItem
Set fldr = Nothing
End Function
非常感谢
安德鲁
更新将斜杠“\”添加到捕获的目录末尾似乎已解决此问题。已更改上面的代码以反映此更改。
【问题讨论】:
-
您在使用
GetFolder时遇到错误吗?对我来说似乎工作得很好。 -
@Robin 没有错误,它不会加载我想要处理的任何文件。 'MsgBox "StrFile = " & strFile' 显示为空。 strDir 取值 ok 并且我选择的文件夹被取走了,但没有一个文件被转换为 Excel。