Summary
An Outlook VBA script intended to auto-print email attachments failed to exclude files containing -PK in their names. The issue arose because the script lacked a filename validation check, causing all matching file types (e.g., .pdf) to be printed regardless of their name.
Root Cause
The script did not include logic to filter filenames containing -PK. The Select Case statement only checked file extensions, ignoring the filename itself.
Why This Happens in Real Systems
- Lack of filename validation: Scripts often focus on file extensions, neglecting specific naming patterns.
- Assumptions about file names: Developers may assume filenames follow a predictable format, which is not always true.
- Overly broad file type checks: The script processed all
.pdffiles without additional criteria.
Real-World Impact
- Unnecessary prints: Files with
-PKwere printed, wasting resources. - User frustration: Unexpected behavior led to confusion and inefficiency.
- Potential data exposure: Sensitive files with
-PKwere printed without intent.
Example or Code
Sub TargetFolderItems_ItemAdd(ByVal Item As Object)
On Error Resume Next
Dim colAtts As Outlook.Attachments
Dim oAtt As Outlook.Attachment
Dim sFile As String
Set colAtts = Item.Attachments
If colAtts.Count Then
For Each oAtt In colAtts
Dim sFileType As String
sFileType = LCase$(Right$(oAtt.FileName, 4))
If InStr(1, oAtt.FileName, "-PK", vbTextCompare) = 0 Then ' Exclude files with -PK
Select Case sFileType
Case ".docx", ".pdf", ".doc", ".pdf"
sFile = FILE_PATH & oAtt.FileName
oAtt.SaveAsFile sFile
ShellExecute 0, "print", sFile, vbNullString, vbNullString, 0
End Select
End If
Next
End If
End Sub
How Senior Engineers Fix It
- Add filename validation: Check for
-PKusingInStrbefore processing. - Use regular expressions: For complex patterns, implement regex-based filtering.
- Test edge cases: Validate the script against various filenames and extensions.
Why Juniors Miss It
- Focus on file types: Juniors often prioritize extensions over filenames.
- Lack of real-world testing: Insufficient testing with diverse file names.
- Overlooking edge cases: Failure to consider specific naming conventions.