首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計疑難解答

VB6 依檔名後綴執行不同列印邏輯:_1.jpg 列印一次、_2.jpg 列印兩次

     編輯:程式設計疑難解答

需求說明

固定目錄下存在多張圖片,檔名格式為 A_1.jpg、A_2.JPG 等。程式需掃描目錄,根據底線後的數字決定列印次數:

  • 檔名含 _1.jpg(不分大小寫) → 執行一次 PrintForm
  • 檔名含 _2.jpg → 執行兩次 PrintForm

實作方案(VB6 純函式)

Option 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

關鍵點說明

  1. 使用 FileSystemObject 需參考 Microsoft Scripting Runtime (scrrun.dll)。
  2. InStrRev 從右尋找底線,確保抓取最後一個底線後的數字。
  3. LCase$ 處理副檔名大小寫差異(.jpg / .JPG)。
  4. 若需遞迴子目錄,可改用遞迴函式或 Dir 配合 vbDirectory。

替代方案:使用 Dir 函式(無需額外參考)

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 函式輕鬆實現依檔名後綴決定列印次數,關鍵在於字串剖析與大小寫正規化。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved