【问题标题】:Get the value before the ubound each time每次获取ubound之前的值
【发布时间】:2020-12-06 20:23:44
【问题描述】:
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。还是我必须另辟蹊径。谢谢马克斯

【问题讨论】:

  • reference(UBound(reference)-1)?
  • BigBen 是对的,就这么简单(为什么不)——你只需要确保 Ubound(a) > 0,否则你会得到一个“下标超出范围”的错误跨度>
  • 只是为了好奇:你是怎么想到在方括号中写 [4] 的——这很不常见(而且是多余的),前段时间我对 SO 的含义有疑问 stackoverflow.com/q/54579404/7599798
  • 感谢 BigBen 和 FunThomas 的回复,[4] 是列索引,我知道它并不常见,但不幸的是我养成了这个习惯。
  • @MaxMurrell - 阅读来自@FunThomas 的问题,我在 cmets 中看到了这个 - [] 也可以在访问表的列时使用,例如 Range("Table[Col1]" ) – Mistella 2019 年 2 月 7 日 18:13。所以,我明白你为什么要使用它......但是......代表每个“继承”VBA代码并且在重写之前必须了解所写内容的VBA开发人员,请停止使用[]列。谢谢:)

标签: excel vba excel-2007 export-to-excel


【解决方案1】:

基本上有 2 种方法可以选择 prelast 值。

选项 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

这个函数稍微好一点,因为它会检查空数组。

【讨论】:

  • @MaxMurrell - 欢迎您。另外,如果你要分割一个空格,比如reference = Split(txt, " "),你可以将代码缩短到这个引用 = Split(txt)`,VBA 会明白你的意思。
猜你喜欢
  • 1970-01-01
  • 2013-09-09
  • 2012-07-08
  • 2011-07-25
  • 2015-04-17
  • 2013-07-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多