2017-01-16 60 views
0

我有一个代码来计算文件夹中的文件,如果它们的名称中包含特定的字符串。将用户表单结果传递给vba代码变量

例如:如果我想让它计算名称上近的文件(Close_26_03_2003.csv)。

当前代码读取工作表中单元格的值,并使用(InStr函数)在文件名中搜索该字符串。问题是我必须在单元格中写入文件的类型。

我想要做的是创建一个用户窗体,有三个选项按钮(打开,关闭和取消)。对于打开它将字符串设置为打开,并搜索名称上的文件(与关闭相同)。取消结束子。

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

守则是:

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 

任何想法?

+0

[调用用户窗体并返回值]的可能副本(http:// sta ckoverflow.com/questions/18966137/calling-a-userform-and-returning-a-value) – Carrosive

回答

1

添加下面的代码在你的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代码如下所示

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 
+0

感谢您的回答。几件事情:在这种情况下,GetValue函数返回一个特定的值(1,2或3)。如果它是2,那么代码如何通过Close? 第二:我在关闭中出现类型不匹配。用户窗体(我改名为我自己的)。 – DGMS89

+1

见编辑答案。如果它解决了你的问题,你可能需要将答案标记为已接受。谢谢! – user3598756