固定目錄下存在多張圖片,檔名格式為 A_1.jpg、A_2.JPG 等。程式需掃描目錄,根據底線後的數字決定列印次數:
_1.jpg(不分大小寫) → 執行一次 PrintForm_2.jpg → 執行兩次 PrintFormOption Explicit
Private Sub PrintImagesBySuffix(folderPath As String)
Dim fso As New FileSystemObject
Dim folder As Folder
Dim file As File
Dim suffix As String
Dim printCount As Long
Set folder = fso.GetFolder(folderPath)
For Each file In folder.Files
suffix = LCase$(fso.GetExtensionName(file.Name)) ' 取副檔名
If suffix = "jpg" Or suffix = "jpeg" Then
' 取得底線後、副檔名前的數字
Dim pos As Long
pos = InStrRev(file.Name, "_")
If pos > 0 Then
Dim numStr As String
numStr = Mid$(file.Name, pos + 1)
numStr = Left$(numStr, InStr(numStr, ".") - 1)
If IsNumeric(numStr) Then
printCount = CLng(numStr)
If printCount > 0 Then
' 這裡放入實際列印邏輯,示範用 Debug.Print
Dim i As Long
For i = 1 To printCount
Debug.Print "PrintForm -> "; file.Path; " 第 "; i; " 次"
' PrintForm ' 實際列印取消註解
Next i
End If
End If
End If
End If
Next file
End Sub
' 呼叫範例
Private Sub Command1_Click()
PrintImagesBySuffix "C:\Images\"
End Sub
FileSystemObject 需參考 Microsoft Scripting Runtime (scrrun.dll)。InStrRev 從右尋找底線,確保抓取最後一個底線後的數字。LCase$ 處理副檔名大小寫差異(.jpg / .JPG)。Dir 配合 vbDirectory。Private Sub PrintImagesDir(folderPath As String)
Dim fileName As String
Dim fullPath As String
Dim pos As Long, numStr As String, printCount As Long
If Right$(folderPath, 1) <> "\" Then folderPath = folderPath & "\"
fileName = Dir$(folderPath & "*.jpg")
Do While fileName <> ""
fullPath = folderPath & fileName
pos = InStrRev(fileName, "_")
If pos > 0 Then
numStr = Mid$(fileName, pos + 1)
numStr = Left$(numStr, InStr(numStr, ".") - 1)
If IsNumeric(numStr) Then
printCount = CLng(numStr)
Dim i As Long
For i = 1 To printCount
Debug.Print "PrintForm -> "; fullPath; " 第 "; i; " 次"
Next i
End If
End If
fileName = Dir$
Loop
End Sub
VB6 可透過 FileSystemObject 或傳統 Dir 函式輕鬆實現依檔名後綴決定列印次數,關鍵在於字串剖析與大小寫正規化。