从 EXcel VBA 中的 Join() 函数中删除定界符

Remove delimiters from Join() Function in EXcel VBA

我是一名新手程序员,我正在通过 VBA 为 excel 构建一个表单,用户将在其中通过 16 个文本框输入员工的时间 sheet 和他们的姓名首字母形式。文本框数据存储到字符串数组中。代码是:

Dim initials(15) As String
initials(0) = TB_Initials_1
initials(1) = TB_Initials_2
initials(2) = TB_Initials_3
...
initials(15) = TB_Initials_15

在使用查找函数并从 excel sheet 中引用一些数据后,我使用

ActiveCell.Offset(0, 2).Value = Join(initials, ".")

输出如下 "js.rs.............." 到另一个 excel sheet 中的活动单元格,(我只输入了 16 个输入框中的 2 个,因此有两个首字母。JS.RS 尾随 ................ 是我要删除的内容。这将在稍后通过 excel sheet 导入到数据库中。 我怎样才能删除字符串末尾的 xtras ".........'s?我已经尝试了 "Trim()" 函数,但这在我的情况下不起作用。一切我在网上试过似乎也不起作用,或者引用的是工作簿中的项目,而不是文本框。 感谢任何帮助。

完整代码如下:

Option Explicit
  'Variable declaration
    Dim startTime(15), endTime(15), ST_Finish_Date As Date
    Dim totalmin(15), Total_min, Total_Cost, Rate(15), Line_cost(15), Cost_Per_Part As String
    Dim initials(15) As String
    Dim i, ii As Integer
    Dim Found_ini(15) As Range
    Dim Found As Range 'returned value from find
    Dim TBtraveller_value As String 'text box traveller value
    Dim Found2 As Range 'store part code range
    Dim TBDESC As Range ' Returned value from 2nd search
    Dim BL_Find_Check As Boolean
    

Private Sub CB_Write_Click()

create_csv
End Sub

Private Sub Close_Form_Click()
Unload Traveller_Entry
End Sub


'still need to make this for every start / stop time text box.

Private Sub TB_Time_Start_1_BeforeUpdate(ByVal Cancel As MSForms.ReturnBoolean)

Dim myvar As String

If Not Me.TB_Time_Start_1 Like "??:??" Then
MsgBox "Please use format 'HH:MM'"

Cancel = True
Exit Sub
End If
myvar = Format(Me.TB_Time_Start_1, "hh:mm")
Me.TB_Time_Start_1 = myvar

End Sub


     Public Sub travellerNUM_TextBox_Exit(ByVal Cancel As MSForms.ReturnBoolean)
  
    Workbooks("Traveller entryxlsm.xlsm").Activate
    TBtraveller_value = travellerNUM_TextBox.Value
        
         If TBtraveller_value = "" Then
    
        MsgBox ("Enter a Shop Traveller Number!")
        Exit Sub
    
    Else
   TBtraveller_value = travellerNUM_TextBox.Value
   Set Found = Sheets("woss").Range("A:A").Find(what:=TBtraveller_value, lookat:=xlWhole)
     

            If Found Is Nothing Then
            MsgBox (TBtraveller_value & " Not Found!")
            Exit Sub
        
            Else
                  
            Part_Code_BOX.Value = Found.Offset(0, 1) 'enters the info into the Part Code Box.
            Set Found2 = Found.Offset(0, 1)
       End If
       
       If Part_Code_BOX = "" Then
       MsgBox ("Traveller number " & TBtraveller_value & " has no part code associated with it." & vbCrLf & "Check Work Order Spread Sheet is FULLY Complete.")
       BL_Find_Check = True
       Exit Sub
       End If
       
            Set TBDESC = Sheets("ProductList").Range("B:B").Find(what:=Found2, lookat:=xlPart)
            If TBDESC Is Nothing Then
            MsgBox (" Dscription Not Found!")
            
           Else
            
            Desc_Box = TBDESC.Offset(0, 1) 'enters the description into the description Box.
            FinishDate_Box = Found.Offset(0, 8) 'enters the finish date into the finish date Box.
            Employee = Found.Offset(0, 2) 'enters the Employee name into the employee name Box.
           
           End If
    
    
            End If
    
 
End Sub




Public Sub CB_POST_Click()


On Error Resume Next

     startTime(0) = TB_Time_Start_1.Value
     startTime(1) = TB_Time_Start_2.Value
     startTime(2) = TB_Time_Start_3.Value
     startTime(3) = TB_Time_Start_4.Value
     startTime(4) = TB_Time_Start_5.Value
     startTime(5) = TB_Time_Start_6.Value
     startTime(6) = TB_Time_Start_7.Value
     startTime(7) = TB_Time_Start_8.Value
     startTime(8) = TB_Time_Start_9.Value
     startTime(9) = TB_Time_Start_10.Value
     startTime(10) = TB_Time_Start_11.Value
     startTime(11) = TB_Time_Start_12.Value
     startTime(12) = TB_Time_Start_13.Value
     startTime(13) = TB_Time_Start_14.Value
     startTime(14) = TB_Time_Start_15.Value
     startTime(15) = TB_Time_Start_16.Value
     
     endTime(0) = TB_Time_Stop_1.Value
     endTime(1) = TB_Time_Stop_2.Value
     endTime(2) = TB_Time_Stop_3.Value
     endTime(3) = TB_Time_Stop_4.Value
     endTime(4) = TB_Time_Stop_5.Value
     endTime(5) = TB_Time_Stop_6.Value
     endTime(6) = TB_Time_Stop_7.Value
     endTime(7) = TB_Time_Stop_8.Value
     endTime(8) = TB_Time_Stop_9.Value
     endTime(9) = TB_Time_Stop_10.Value
     endTime(10) = TB_Time_Stop_11.Value
     endTime(11) = TB_Time_Stop_12.Value
     endTime(12) = TB_Time_Stop_13.Value
     endTime(13) = TB_Time_Stop_14.Value
     endTime(14) = TB_Time_Stop_15.Value
     endTime(15) = TB_Time_Stop_16.Value

    initials(0) = TB_Initials_1
    initials(1) = TB_Initials_2
    initials(2) = TB_Initials_3
    initials(3) = TB_Initials_4
    initials(4) = TB_Initials_5
    initials(5) = TB_Initials_6
    initials(6) = TB_Initials_7
    initials(7) = TB_Initials_8
    initials(8) = TB_Initials_9
    initials(9) = TB_Initials_10
    initials(10) = TB_Initials_11
    initials(11) = TB_Initials_12
    initials(12) = TB_Initials_13
    initials(13) = TB_Initials_14
    initials(14) = TB_Initials_15
    initials(15) = TB_Initials_16
    
    For i = LBound(initials) To UBound(initials)
    
    
    Set Found_ini(i) = Sheets("rate").Range("B:B").Find(what:=initials(i), lookat:=xlWhole)
    Rate(i) = Found_ini(i).Offset(0, 1) 'finds rate for given initials
     totalmin(i) = DateDiff("N", startTime(i), endTime(i))
     
     
If Found_ini(i) Is Nothing Then
            MsgBox (initials(i) & " Not Found! Update Employee Database.")
            Exit Sub
            
   'If IsEmpty(Found_ini(i)) = False And IsEmpty(startTime(i)) = True And IsEmpty(endTime(i)) = True Then
        
    'MsgBox "Enter Some Initials, None Found"
     Exit Sub

    End If
    Next
    
   
 
 For ii = LBound(totalmin) To UBound(totalmin)
 Line_cost(ii) = totalmin(ii) / 60 * Rate(ii)
                    
     Next
 
    Total_min = Application.WorksheetFunction.Sum(totalmin)
    Total_Cost = Application.WorksheetFunction.Sum(Line_cost)
    Cost_Per_Part = Total_Cost / TextBOX_QTYBUILT
  
   If Total_min = 0 Then
        MsgBox (" Enter Some Time!")
     
    ElseIf Total_min < 0 Then
        MsgBox ("Time is NEGATIVE. Check Entered Times.")
                 
End If

If BL_Find_Check = False Then

MsgBox "The number of minutes between two Times : " & Total_min & vbNewLine & "total cost: " & Total_Cost _
          & vbNewLine & "cost Per Part " & Cost_Per_Part, vbInformation, "Minutes Between Two Times"


Sheets("test").Select
Range("A1048576").Select
        ActiveCell.End(xlUp).Select
        ActiveCell.Offset(1, 0).Select
        ActiveCell.Offset(0, 0).Value = FinishDate_Box 'Traveller finish Date
        ActiveCell.Offset(0, 1).Value = TBtraveller_value 'Traveller Number
        ActiveCell.Offset(0, 2).Value = Join(initials, ".") 'Traveller Employee Given to
        ActiveCell.Offset(0, 3).Value = Part_Code_BOX.Value ' part number
        ActiveCell.Offset(0, 4).Value = Total_Cost ' traveller total cost
        ActiveCell.Offset(0, 5).Value = Cost_Per_Part 'Traveller cost per part
       
      
End If

End Sub


Sub create_csv()
    Dim FileName As String
    Dim PathName As String
    Dim ws As Worksheet

    Set ws = ActiveWorkbook.Sheets("test")
    FileName = "CSV_Output_R1.csv"
    PathName = Application.ActiveWorkbook.Path
    ws.Copy
    ActiveWorkbook.SaveAs FileName:=PathName & "\" & FileName, _
        FileFormat:=xlCSV, CreateBackup:=False
        
End Sub


谢谢,

您可以像这样构建它而不是使用 Join():

ActiveCell.Offset(0, 2).Value = initials(0)

For Counter = 1 To 15
  If initials(Counter) <> "" Then
    ActiveCell.Offset(0, 2).Value = ActiveCell.Offset(0, 2).Value + "." + initials(Counter)
  End If
Next Counter

这是我刚刚创建的一个函数,用于 trim 数组末尾的空元素:

Function TrimArray(ByRef StringArray() As String) As String()
    'This function removes trailing empty elements from arrays
    
    'Searching from the last element backwards until a non-blank is found
    Dim i As Long
    For i = UBound(StringArray) To LBound(StringArray) Step -1
        If StringArray(i) <> "" Then Exit For
    Next i
    If i < LBound(StringArray) Then i = LBound(StringArray)
    
    'Creating an array with the correct size to hold the non-blank elements
    Dim OutArr() As String
    OutArr = StringArray
    ReDim Preserve OutArr(LBound(StringArray) To i)
    
    TrimArray = OutArr
End Function

您可以这样使用它:

    Dim Output() As String
    Output = TrimArray(initials)
    MsgBox Join(Output, ".") & "."

在Excel2019+中可以在一个字符串中使用WorksheetFunction.TextJoin()

ActiveCell.Offset(0, 2).Value = WorksheetFunction.TextJoin(".", True, initials)

比较的小例子:

Sub test1()
    Dim arr(1 To 15)
    For i = 1 To 15
        arr(i) = IIf(Rnd() > 0.7, "TXT", "")
    Next
    Debug.Print "With Join(): " & Join(arr, ".")
    Debug.Print "With TextJoin(): " & WorksheetFunction.TextJoin(".", True, arr)
End Sub

输出

With Join(): ..TXT........TXT..TXT..
With TextJoin(): TXT.TXT.TXT