excel - 将项目添加到集合时更改单元格颜色
问题描述
目前,我有一个宏,可以查找随机放入文件夹/子文件夹中的文件,如果通过阅读 B 列中的列表找到它们,则打开它们。它工作得很好,但如果该文件不存在,它只会跳过单元格,如果找不到,我想更改单元格的颜色。代码的上半部分来自其他人,我尝试过修改它,但找不到让这种情况发生的方法。它不会添加不存在的文件路径,而是跳过它。
Sub GetFiles(StartFolder As String, Pattern As String, _
DoSubfolders As Boolean, ByRef colFiles As Collection)
Dim f As String, sf As String, subF As New Collection, s
If Right(StartFolder, 1) <> "\" Then StartFolder = StartFolder & "\"
f = Dir(StartFolder & Pattern)
Do While Len(f) > 0
colFiles.Add StartFolder & f
f = Dir()
Loop
sf = Dir(StartFolder, vbDirectory)
Do While Len(sf) > 0
If sf <> "." And sf <> ".." Then
If (GetAttr(StartFolder & sf) And vbDirectory) <> 0 Then
subF.Add StartFolder & sf
End If
End If
sf = Dir()
Loop
For Each s In subF
GetFiles CStr(s), Pattern, True, colFiles
Next s
End Sub
.
Sub BatchPrint()
Dim colFiles As New Collection
Dim CustRow, LastRow As Long
Set colFiles = New Collection
LastRow = Sheet1.Range("B9999").End(xlUp).Row
With Sheet1
For CustRow = 3 To LastRow
GetFiles "C:\Users\Desktop\Test\", Sheet1.Range("B" & CustRow) & ".pdf", True, colFiles
Next CustRow
End With
Dim i As Long
For i = 1 To colFiles.Count
FollowHyperlink colFiles(i)
Next i
Set colFiles = Nothing
End Sub
解决方案
我只是在代码中添加了一些行。在变量 countFiles 中,在获取下一个文件之前存储找到的文件的数量。如果未找到,则保留找到的文件数。在这种情况下,单元格将被着色。
Sub BatchPrint()
Dim colFiles As New Collection
Dim CustRow, LastRow As Long
Set colFiles = New Collection
LastRow = Sheet1.Range("B9999").End(xlUp).Row
Dim countFiles As Integer 'Storing the number of files found
With Sheet1
For CustRow = 3 To LastRow
countFiles = colFiles.Count
GetFiles "C:\Users\Desktop\Test\", Sheet1.Range("B" & CustRow) & ".pdf", True, colFiles
If countFiles = colFiles.Count Then
'No new files, shall change the color of the cell
Sheet1.Range("B" & CustRow).Interior.ColorIndex = 3
End If
Next CustRow
End With
Dim i As Long
For i = 1 To colFiles.Count
FollowHyperlink colFiles(i)
Next i
Set colFiles = Nothing
End Sub
推荐阅读
- python - 在 Pandas 中读取自定义稀疏格式
- sanity - Sanity io 显示作者的博客文章
- typescript - 使用泛型接口的泛型函数
- python - 将 Twitter 数据的大型 JSONL (32gb) 转换为 CSV 或数据帧(R 或 Python)
- calendar - Nextcloud:如何更改数据库中日历事件的颜色?
- r - 如何重塑数据框,使每个 id 只有 1 个观察值?
- amazon-web-services - 使用 AWS CLI 为 AWS Cognito 池生成访问令牌
- assembly - 使用命名堆栈参数编写一个过程
- salesforce - 尝试将重定向页面上的输出链接添加到来自另一个 VF 页面的新创建的机会
- python-3.x - 在分割模型库中将最终预测的图像尺寸改回其原始尺寸