代码之家  ›  专栏  ›  技术社区  ›  hughdbrown

将VBA移植到VB.NET:函数参数可能是多维数组

  •  1
  • hughdbrown  · 技术社区  · 16 年前

    以下是简化代码:

    Public Function Stat(ByVal Data As Range) As Object
        Dim Y() As Object
        Dim Appp As New Application() ''// Very annoying
    
        ''//Convert worksheet range into array vector
        Y = Appp.WorksheetFunction.Transpose(Appp.WorksheetFunction.Transpose(Data))
    
        Dim dimensions As Integer : dimensions = NumberOfArrayDimensions(Y)
    
        If dimensions > 1 Then
            For i = LBound(Y) To UBound(Y)
                If VarType(Y(i, 1)) <> 0 Then
    

    编辑:所以问题是这样的,“如何在VB.NET中像在Excel VBA中一样使用单个变量--具有不明确/灵活的维度?”如果没有,则“您建议如何在VB.NET中将代码更改为最自然的?”

    2 回复  |  直到 16 年前
        1
  •  1
  •   Fredrik Mörk    16 年前

    因为我没有样本数据,所以这是未经测试的,但类似的东西可能会起作用:

    Dim dimensions As Integer : dimensions = Y.Rank
    
    If dimensions > 1 Then
        For i = Y.GetLowerBound(0) To Y.GetUpperBound(0)
            If VarType(Y.GetValue(i, 1)) <> 0 Then
    

    Y.Rank 将返回维度数(我假设这将导致与调用相同的值) NumberOfArrayDimensions(Y) ).

    编辑:我认为您还需要更改 Y 为此:

    Dim Y As Array
    
        2
  •  0
  •   shahkalpesh    16 年前
    Public Function Stat(ByVal Data As Range) As Object
    Dim Y() As Object
    Dim Appp As New Application() ''// Very annoying
    
    dim rows as Integer
    dim cols as Integer
    
    dim rowCtr as Integer = 1
    dim colCtr as Integer = 1
    
    rows = Data.Rows.Count
    cols = Data.Columns.Count
    
    Y = Appp.WorksheetFunction.Transpose(Appp.WorksheetFunction.Transpose(Data))
    
    for rowCtr = 1 to rows
      for colCtr = 1 to cols
         Debug.Print Y(rowCtr, colCtr)
      next
    next
    


    我没有修改代码的其余部分(除了查找维度),这需要一些改进。

    EDIT2:因为转置返回一个数组,其边界从1开始。
    EDIT3:上面的代码是VB6样式的。但是VB.net中的想法仍然相同