这是我的代码:
Private Sub UserForm_Initialize()
Dim MyFolder As String
Dim MyFile As String
Dim j As Integer
Dim Funds(1000)
CD_Date = Cells(1, 4)
Range("A2").Select
i = 1
Do
Funds(i) = UCase(ActiveCell.Value)
i = i + 1
ActiveCell.Offset(1, 0).Select
Loop Until ActiveCell.Value = ""
MyFolder = "C:\windows\"
r = 0
For k = 1 To i - 1
MyFile = Dir$(MyFolder & "*" & Funds(k) & "*")
Do While MyFile <> ""
datka = FileDateTime(MyFolder & MyFile)
If Format(datka, "yymmdd") = Format(CD_Date, "yymmdd") Then
With UserForm1.ListBox1
.AddItem
.List(r, 0) = Funds(k)
.List(r, 1) = MyFile
r = r + 1
End With
End If
MyFile = Dir$
Loop
Next k
Range("A2").Select
End Sub
代码完美无缺,但是当我在前一天或当前时移动CD_Date
时,它不会动态更改 - 2.它总是为输入的日期添加项目,仅用于首次运行。当我在单元格中更改日期时,它总是从第一次初始化返回列表。当我关闭文件并再次打开它时,它会重置,每次都是不同的日期。在我更改CD_Date
或有人将文件添加到文件夹后,是否可以修改我将动态填充的代码?我想避免关闭并打开宏来反复获取实际数据:(
答案 0 :(得分:0)
您可以添加循环以从代码中添加项目之前的ListBox中删除所有项目,以便每次都有效地刷新它。要做到这一点,你正在寻找类似的东西:
With UserForm1.ListBox1
For i = 1 to .ListCount
.RemoveItem(0)
Next i
End With
在你的代码中,似乎每次打开表单时你只需要ListBox中的一个项目,所以尽管这里的循环是不必要的,但这是一个很好的记忆方法。在添加项目之前尝试将其放入模块中:
Private Sub UserForm_Initialize()
Dim MyFolder As String
Dim MyFile As String
Dim j As Integer
Dim Funds(1000)
CD_Date = Cells(1, 4)
Range("A2").Select
i = 1
Do
Funds(i) = UCase(ActiveCell.Value)
i = i + 1
ActiveCell.Offset(1, 0).Select
Loop Until ActiveCell.Value = ""
MyFolder = "C:\windows\"
r = 0
For k = 1 To i - 1
MyFile = Dir$(MyFolder & "*" & Funds(k) & "*")
Do While MyFile <> ""
datka = FileDateTime(MyFolder & MyFile)
If Format(datka, "yymmdd") = Format(CD_Date, "yymmdd") Then
With UserForm1.ListBox1
For i = 1 to .ListCount 'Here
.RemoveItem(0)
Next i
.AddItem
.List(r, 0) = Funds(k)
.List(r, 1) = MyFile
r = r + 1
End With
End If
MyFile = Dir$
Loop
Next k
Range("A2").Select
End Sub