我有一个代码可以计算文件夹中的文件,如果它们的名称中包含特定的字符串。
例如:如果我想让它计算名字上带有close的文件(Close_26_03_2003.csv)。
目前,代码读取工作表中单元格的值,并使用(InStr函数)在文件名中搜索该字符串。问题是我必须在单元格中写入文件类型。
我要做的是创建一个用户表单,有三个选项按钮(打开,关闭和取消)。对于open,它将字符串设置为open,并搜索在其名称上包含它的文件(与close相同)。取消结束子。
问题是我不知道我必须在用户表单中使用哪些代码,并且不知道如何将其传递给计算文件的代码(我将其分配给变量) )。
代码原样:
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 :(得分: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
代码更改为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