【问题标题】:Declaring array size in Visual Basic在 Visual Basic 中声明数组大小
【发布时间】:2011-12-16 17:34:01
【问题描述】:

这是我第一次使用 VB。我主要习惯于在 matlab 中工作,并且发现我在 matlab 中认为理所当然的许多东西必须在 VB 中显式声明。令人沮丧!

特别是我需要声明两个数组大小 s1 和 s2。正如您在下面的代码中看到的,s1 是集合“n”中的元素数,其中变量“stratum”等于 1。s2 是集合“n”中的元素数,其中变量“stratum”等于 2。漂亮直截了当。

我的方法是简单地将层变量 1 循环到 n 并计算这些出现次数;然后将结果总和声明为常数。这在 matlab 中可以很好地工作,但 VB 不接受 s1 和 s2 作为常量。当我在循环后插入 debug.print 命令时,它甚至不会显示 s1 和 s2。

我已经浏览了已经发布的相关帖子。我很感激任何建议。谢谢。

    Sub TOAinput()

    Const n As Integer = 648

    Dim stratum(n), hybrid(n), acres(n), hhsz(n), offinc(n)

    For i = 1 To n
        stratum(i) = Worksheets("hhid level").Cells(i + 1, 2).Value
    Next i

    Dim s1 As Integer
    Dim s2 As Integer


    s1 = 0
    s2 = 0
    For i = 1 To n
        If stratum(i) = 1 Then
            s1 = s1 + 1
        Else:
            s2 = s2 + 1
        End If
    Next i

    Dim acres1(s1), hhsz1(s1), offinc1(s1), acres2(s2), hhsz2(s2), offinc2(s2)

    (...)
    End Sub

【问题讨论】:

    标签: arrays excel vba


    【解决方案1】:

    这对你来说应该会更好一些:

    Sub TOAinput()
    
    Const n As Integer = 648
    
    Dim stratum(n) As Integer
    Dim hybrid(n) As Integer
    Dim acres(n) As Integer
    Dim hhsz(n) As Integer
    Dim offinc(n) As Integer
    
    Dim i As Integer
    
    For i = 1 To n
        stratum(i) = Worksheets("hhid level").Cells(i + 1, 2).Value
    Next
    
    Dim s1 As Integer
    Dim s2 As Integer
    
    For i = 1 To n
        If stratum(i) = 1 Then
            s1 = s1 + 1
        Else
            s2 = s2 + 1
        End If
    Next
    
    Dim acres1() As Integer
    Dim hhsz1() As Integer
    Dim offinc1() As Integer
    Dim acres2() As Integer
    Dim hhsz2() As Integer
    Dim offinc2() As Integer
    
    ReDim acres1(s1)
    ReDim hhsz1(s1)
    ReDim offinc1(s1)
    ReDim acres2(s2)
    ReDim hhsz2(s2)
    ReDim offinc2(s2)
    
    (...)
    End Sub
    

    如果可能,我还建议您在数组上声明类型。我假设它们都是整数并适当地修改了代码,但这可能不适用于您的情况(即不同的数据类型)。

    【讨论】:

    • Dim sumac1, sumac2, mhhsz1, mhhsz2, cvhhsz1, cvhhsz2 sumac1 = Sum(acres1) sumac2 = Sum(acres2) mhhsz1 = Average(hhsz1) mhhsz2 = Average(hhsz2) cvhhsz1 = StDev(hhsz1) / 平均(hhsz1) cvhhsz2 = 标准差(hhsz2) / 平均(hhsz2)
    • 非常感谢。忽略我不小心发布的胡言乱语。
    【解决方案2】:

    几个cmets:

    如果您在代码中更改 s1 和 s2 的值(就像您在 for 循环中一样),则不应将它们声明为 Const。您似乎还试图在声明之前使用 s1 和 s2。

    我不确定您究竟想用“Const s1 As Integer = s1”语句做什么。您可能只想要代码顶部附近的“Dim s1 as Integer”和“Dim s2 as Integer”。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-14
      • 1970-01-01
      • 1970-01-01
      • 2017-03-30
      • 2011-03-23
      相关资源
      最近更新 更多