【问题标题】:update string when calling sub on loop vba excel在循环vba excel上调用子时更新字符串
【发布时间】:2017-01-13 17:55:55
【问题描述】:

你好!

我的项目中有一个循环,在循环中我调用一个子 (Stcount) 来计算元素的列号。该子以随每个循环而变化的字符串(ststring)为食。但是,子 (Stcount) 似乎无法识别字符串 (ststring) 的变化。

首先,我首先定义一些我将用于此序列的变量

Public counterSt As Integer
Public ststring As String
Public rng As Range
Public rng2 As Range

在这个子中,我定义了将成为我的子基础的字符串

Sub test()

Dim Stx(9) As String
    Stx(1) = "Stx1"
    Stx(2) = "Stx2"
    Stx(3) = "Stx3"
    Stx(4) = "Stx4"
    Stx(5) = "Stx5"
    Stx(6) = "Stx6"
    Stx(7) = "Stx7"
    Stx(8) = "Stx9"
    Stx(9) = "Stx10"

Set rng2 = Range("G10")
For i = 1 To 9
    ststring = "ist_" & Stx(i)
    Call StCount
    rng2.Value = counterSt
    Set rng2 = rng2.Offset(1, 0)

Next i

End Sub

当我调用 StCount 时,它会更新 counterSt 的值。对于第一个字符串,它工作正常。但是当它循环时,它似乎没有识别出它应该使用一个新字符串(ststring)。因此,它每次都返回相同的值!

Sub StCount()
Set rep = ActiveWorkbook.Sheets("Sheet2")
Set sh1 = ActiveWorkbook.Sheets("Sheet1")


    Dim trng As Range
    Set trng = rep.Range("A4:HV4")

    For Each rng In trng
        If rng.Value = ststring Then
        counterSt = Range(rng, rng.End(xlToLeft)).Columns.count
        End If
    Next rng
End Sub

作为检查,我尝试查看 Ststring 是否已正确更新(确实如此)。我还尝试手动更新 ststring 的值,并使用不同的 ststring 在同一个 sub 中调用 StCount 不同时间(它也有效)。因此,我认为问题出在循环上。

想法?

【问题讨论】:

  • Salut,Set trng = rep.Range("A4:HV4") 永远不会改变,如果这不改变你将总是循环通过相同的范围,我不认为这是你想要吗?
  • Trng 是表头所在的位置。所以我确实希望它保持固定,因为我想知道列号是什么

标签: string vba excel loops


【解决方案1】:

您的代码对我来说很好,但我认为不需要公共变量。我建议更像这样的东西:

Sub test()
    Dim rng2                  As Range
    Dim i                     As Long
    Dim Stx(9)                As String

    Stx(1) = "Stx1"
    Stx(2) = "Stx2"
    Stx(3) = "Stx3"
    Stx(4) = "Stx4"
    Stx(5) = "Stx5"
    Stx(6) = "Stx6"
    Stx(7) = "Stx7"
    Stx(8) = "Stx9"
    Stx(9) = "Stx10"

    Set rng2 = Range("G10")
    For i = 1 To 9
        rng2.Value = StCount("ist_" & Stx(i))
        Set rng2 = rng2.Offset(1, 0)

    Next i

End Sub
Function StCount(sTest As String)
    Dim rng                   As Range
    Dim trng                  As Range
    Dim rep                   As Worksheet
    Dim sh1                   As Worksheet
    Set rep = ActiveWorkbook.Sheets("Sheet2")
    Set sh1 = ActiveWorkbook.Sheets("Sheet1")


    Set trng = rep.Range("A4:HV4")

    For Each rng In trng
        If rng.Value = sTest Then
            StCount = Range(rng, rng.End(xlToLeft)).Columns.Count
            Exit For
        End If
    Next rng
End Function

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-12-29
    • 1970-01-01
    • 2018-03-24
    • 1970-01-01
    • 2014-09-19
    • 2016-10-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多