欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

【VBA】自定义函数,将数组中的元素连接起来(可以每个元素两边分别加字符)

程序员文章站 2022-05-01 19:54:19
方便在sql拼接时使用'自定义函数,将数组中的元素连接起来(可以每个元素两边分别加字符)'By Gao Dawei,2020-10-09Function ArrayJoin(ByVal arr As Variant, Optional element_plugin_left As String = "", _ Optional element_plugin_right As String = "", Optional delimiter As String = ",...

方便在sql拼接时使用

'自定义函数,将数组中的元素连接起来(可以每个元素两边分别加字符)
'By Gao Dawei,2020-10-09
Function ArrayJoin(ByVal arr As Variant, Optional element_plugin_left As String = "", _
                  Optional element_plugin_right As String = "", Optional delimiter As String = ",")
  Dim ele As Variant, n As Long
  Dim arr_result() As String
  
  For Each ele In arr
    n = n + 1
  Next
  ReDim arr_result(1 To n) As String
  n = 0
  For Each ele In arr
    n = n + 1
    arr_result(n) = StringFormat("{1}{0}{2}", ele, element_plugin_left, element_plugin_right)
  Next
  ArrayJoin = Join(arr_result, delimiter)
End Function

'模仿C# string.Format()
'没有设置数量的判断,使用时自己判断好{n}
'例:正常写作 "hello " & str,可以用此函数写作StringFormat("hello {0}",str)
'By Gao Dawei,2020-10-09
Function StringFormat(ByVal str As String, ParamArray arr_replace_with() As Variant)
    Dim item As Variant
    Dim n As Long, n_source As String
    Dim result As String
    
    result = str
    For Each item In arr_replace_with
        n_source = "{" & n & "}"
        result = Replace(result, n_source, item)
        n = n + 1
    Next
    StringFormat = result
End Function

本文地址:https://blog.csdn.net/QQ114152850/article/details/108976307

相关标签: VBA Excel sql