我正在运行一个宏,它自动获取csv文件并将它们导入我工作簿中的特定工作表。但是,我希望通过让用户选择要导入的文件来增加灵活性,而不是让宏自动获取csv文件,因为命名可能会随目录而改变。我是VBA的新手,并且一直在努力更好地理解MsoFileDialogType和GetOpenFilename,但是很难在我的代码中把握概念/实现。
我最终希望用户点击工作簿前端的按钮。系统会提示您选择要导入的第一个csv文件。此csv文件将导入到工作簿temp1中的预先命名的工作表中。但是由于数据文件成对出现,我希望用户能够在第一个文件后选择下一个csv文件到temp2。
目前我所拥有的是:
Worksheets.Add
ActiveSheet.Name = "temp1"
With ActiveSheet.QueryTables.Add(Connection:= _
"TEXT;MAC Directory path here" _
, Destination:=Range("A1"))
.Name = "temp 1 03.02.12"
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.RefreshOnFileOpen = False
.BackgroundQuery = True
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.TextFilePromptOnRefresh = False
.TextFilePlatform = xlMacintosh
.TextFileStartRow = 1
.TextFileParseType = xlDelimited
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = False
.TextFileTabDelimiter = False
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = True
.TextFileSpaceDelimiter = False
.TextFileColumnDataTypes = Array(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, _
1, 1, 1)
.Refresh BackgroundQuery:=False
.UseListObject = False
End With
ActiveSheet.Move after:=Worksheets(Worksheets.Count)
谢谢。
答案 0 :(得分:3)
也许就是这些问题。
Sub GetCSVList()
Dim dlgOpen As FileDialog
Set dlgOpen = Application.FileDialog(msoFileDialogFilePicker)
With dlgOpen
.AllowMultiSelect = True
''Start in
.InitialFileName = "Z:\docs\"
.Show
End With
For Each fname In dlgOpen.SelectedItems
ImportCSV fname
Next
End Sub
Sub ImportCSV(fname)
Set ws = Worksheets.Add(after:=Worksheets(Worksheets.Count))
ws.Name = "temp" & Worksheets.Count + 1
With ws.QueryTables.Add( _
Connection:="TEXT;" & fname, _
Destination:=Range("A1"))
.Name = "Temp" & Worksheets.Count + 1
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.BackgroundQuery = True
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.TextFilePromptOnRefresh = False
.TextFilePlatform = xlMacintosh
.TextFileStartRow = 1
.TextFileParseType = xlDelimited
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = False
.TextFileTabDelimiter = False
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = True
.TextFileSpaceDelimiter = False
.Refresh BackgroundQuery:=False
'.UseListObject = False
End With
End Sub