首页 > 代码库 > VBA小技巧

VBA小技巧

运用VBA时,可以构造一些函数去实现诸如printf的方便函数。

 

Public Function printf(mask As String, ParamArray tokens()) As String
    Dim i As Long
    For i = 0 To UBound(tokens)
        mask = Replace(mask, "{" & i & "}", tokens(i))
    Next
    printf = mask
End Function

Sub test1()
    
    cc = genSearchedArr(6554, "a", "b", "e", "f", "g")
    
    MsgBox cc
End Sub

Function genSearchedLines(searchedRow As Integer, ParamArray columns()) As String
    Dim searchedVal As String
        
    Dim i As Long
    
    For i = 0 To UBound(columns)
    
        If i = 0 Then
            searchedVal = printf("{0}{1}", columns(i), searchedRow)
        Else
            searchedVal = searchedVal & printf("&{0}{1}", columns(i), searchedRow)
        End If
    Next
    
    genSearchedLines = searchedVal
    
End Function

Function genSearchedArr(searchedRow As Integer, ParamArray columns()) As String
    Dim searchedArr As String
    
    Dim i As Long
    
    For i = 0 To UBound(columns)
    
        If i = 0 Then
            searchedArr = printf("{0}1:{0}{1}", columns(i), (searchedRow - 1))
        Else
            searchedArr = searchedArr & printf("&{0}1:{0}{1}", columns(i), (searchedRow - 1))
        End If
    Next
    
    genSearchedArr = searchedArr
    
End Function

  

VBA小技巧