每次获取之前的值

问题描述

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," ")
cells(d + 1,[12]).Value = reference(3)

嗨,我试图每次在ubound值之前选择引用,然后复制到最后一行的引用。当它是字符串的第4部分时,我得到了此代码,但是我试图始终选择ubound之前的值。是否可以做UBOUND -1。还是我必须另辟way径。谢谢麦克斯

解决方法

基本上有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

该功能要好一些,因为它可以检查空数组。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...