将用户表单结果传递给vba代码variables

我有一个代码来计算文件夹中的文件,如果他们的名字包含特定的string。

例如:如果我想要它的名字(Close_26_03_2003.csv)closures的文件数。

目前代码读取工作表中单元格的值,并使用(InStr函数)在文件名称中search该string。 问题是我必须在单元格中写入文件的types。

我想要做的是创build一个用户窗体,有三个选项button(打开,closures和取消)。 对于打开,它将string设置为打开,并search名称上的文件(与closures相同)。 取消结束子。

问题是我不知道哪些代码,我必须在用户窗体中使用,不知道如何将它传递给计数文件的代码(我把它分配给一个variables)。

代码是这样的:

Sub CountFiles3() Dim path As String, count As Integer, i As Long, var As Integer Dim ws As Worksheet Dim Filename As String Dim FileTypeUserForm As UserForm1 Application.Calculation = xlCalculationManual path = ThisWorkbook.path & "\*.*" Filename = Dir(path) 'the problem is here: 'x = user form result*************** 'if cancel = true, end sub Set ws = ThisWorkbook.Sheets("FILES") i = 0 Do While Filename <> "" 'var = InStr(Filename, ws.Cells(2, 7).Value) 'this is current code, it checks if the cell has open or close var = InStr(Filename, x) If var <> 0 Then i = i + 1 ws.Cells(i + 1, 1) = Filename Filename = Dir() Else: Filename = Dir() End If Loop Application.Calculation = xlCalculationAutomatic ws.Cells(1, 2) = i MsgBox i & " : files found in folder" End Sub 

这是我目前的用户表单代码:

 Private Sub Cancel_Click() Me.Tag = 3 ' EndProcess Me.Hide End Sub Private Sub ClosingType_Click() Me.Tag = 2 ' "CLOSING" Me.Hide End Sub Private Sub OpeningType_Click() Me.Tag = 1 ' "OPENING" Me.Hide End Sub 

有任何想法吗?

将下面的代码添加到“”问题在这里:“部分中的CountFiles3()子:

 Dim x As String x = GetValue If x = "end" Then Exit Sub 

然后在任何模块中添加以下代码:

 Function GetValue() With MyUserForm '<--| change "MyUserForm " to your actual UserForm name .Show GetValue = .Tag End With Unload MyUserForm '<--| change "MyUserForm " to your actual UserForm name End Function 

并更改您的Userform代码作为follwos

 Private Sub Cancel_Click() Me.Tag = "end" ' EndProcess Me.Hide End Sub Private Sub ClosingType_Click() Me.Tag = "close" ' "CLOSING" Me.Hide End Sub Private Sub OpeningType_Click() Me.Tag = "open" ' "OPENING" Me.Hide End Sub