如何向我的方法添加自定义搜索过滤器?

时间:2014-10-08 18:31:11

标签: excel vba excel-vba csv

我正在编写一个涉及从文件夹中获取.csv文件的宏。宏要求用户输入文件夹路径,输入后,它将获取文件夹中的所有.csv文件,并在工作簿中创建它们。

我希望宏向用户询问他们想要加载到工作簿中的扩展名。

例如,某些文件名为Chan_41-103.csv,Chan_41-109.csv和Chan_44-103.csv。因此,如果有一种方法可以询问用户他们想要什么文件,他们可以输入“* -103.csv”,宏只会在文件名中带有-103.csv的文件。

我知道我可以直接硬编码“* -103.csv”并且它会这样做,但是,有很多不同名称的文件,我将不得不为一堆文件运行这个宏。如果可以询问用户,那就太好了。

以下是我已有的代码:

Sub CSV_Sheets()
'This takes the .csv file from a specific folder and puts it into the workbook
Dim i As Integer
Dim path As String
Dim Extension As String

Cells(2, 2).Value = InputBox("Extension of File:", "Extension *-#.csv")
Extension = Cells(2, 2).Value & "\"
i = 1
Range("A1").Value = "CSV Folder Path="
Range("A1").HorizontalAlignment = xlRight
Cells(1, 2).Value = InputBox("CSV File Folder Pathway:", "Path Assignment")
path = Cells(1, 2).Value & "\"
Filename = Dir(path & Extension)
Do While Filename <> ""
Workbooks.Open Filename:=path & Filename, ReadOnly:=True
For Each Sheet In ActiveWorkbook.Sheets
    Sheet.Copy After:=ThisWorkbook.Sheets(1)
Next Sheet
Workbooks(Filename).Close
Filename = Dir()
Loop
End Sub

1 个答案:

答案 0 :(得分:1)

Sub test()

Dim FolderPath As String
Dim xlwb As Excel.Workbook
Dim Filename As String
Dim path As String


 FolderPath = "PathToYourFolder"

 path = FolderPath & "\*" & InputBox("Enter the Extension here.", "Extension Retrieval") & ".csv"

 Filename = Dir(path)

 If Filename = "" Then

 ElseIf Filename <> "" Then
    Set xlwb = Excel.Workbooks.Open(FolderPath & "\" & Filename)
 End If

End Sub

星号作为通配符,我使用名为test-104.csv的文件对其进行了测试,它就像魅力一样