每次获取ubound之前的值

Get the value before the ubound each time

Dim txt As String
Dim i As Integer
Dim reference As Variant
Dim d As Integer

d = Worksheets("Sheet1").cells(Rows.Count, "a").End(xlUp).Row
txt = cells(3, 4).Value
reference = Split(txt, " ")

For i = 0 To UBound(reference)
    cells(d + 1, [4]).Value = reference(i)
Next

txt = cells(3, 4).Value
reference = Split(txt, " ")
cells(d + 1, [12]).Value = reference(3)

嗨,我试图每次都在 ubound 值之前选择引用,并将引用复制到最后一行。当它是字符串的第 4 部分时,我得到了这段代码,但我试图始终在 ubound 之前选择值。是否可以执行 UBOUND -1。还是我必须另辟蹊径。谢谢 max

基本上有 2 种方法可以选择前一个值。

选项 1 - 使用 Ubound():

Sub TestMe()

    Dim reference As String
    reference = "Stack Overflow is my favourite VBA site!"
    
    Dim splitted As Variant
    splitted = Split(reference)
    
    Debug.Print splitted(UBound(splitted) - 1)
        
End Sub

选项 2 - 对数组长度使用预定义函数并从中删除 2:

这样称呼:

Debug.Print splitted(GetArrayLength(splitted) - 2)

函数:

Private Function GetArrayLength(myArray As Variant) As Long
    
    If IsEmpty(myArray) Then
        GetArrayLength = 0
    Else
        GetArrayLength = UBound(myArray) - LBound(myArray) + 1
    End If
    
End Function

该函数要好一些,因为它会检查空数组。