2012-12-25 2 views
1

출력 변수를 소프트 코드해야하므로 출력을 수정할 때마다 VBA 코드를 수정할 필요가 없습니다. 가능한 경우 문자열 참조를 변수 이름으로 변환

Sub Working() 
    Dim cat(1 To 10) 
    Dim bat(1 To 10) 

    For i = 1 To 10 
     cat(i) = i * 10 
     bat(i) = i * 5 
    Next i 

    Sheet2.Range("A2:A11") = Application.Transpose(cat()) 
    Sheet2.Range("B2:B11") = Application.Transpose(bat()) 
End Sub 

이 내가 쓰고 싶은 것이 이상적인 방법입니다 작동 코드 만

Sub not_working() 
    Dim cat(1 To 10) 
    Dim bat(1 To 10) 

    For i = 1 To 10 
     cat(i) = i * 10 
     bat(i) = i * 5 
    Next i 

    a = 3 
    Do While Sheet1.Cells(a, 1) <> "" 
     OutVar = Sheet1.cells(a, 1) & "()" 
     Sheet3.Range(_ 
      Cells(2, a - 2).Address, Cells(11, a - 2).Address _ 
     ) = Application.Transpose(Outvar) 
     a = a + 1 
    Loop 
End Sub 

' Sheet1.cells(3,1) = cat - these cells contain the variable names 
' Sheet1.cells(4,1) = bat - these cells contain the variable names 

누군가가 제안 주시겠습니까 나던 작품입니다 그렇게하려면?

+0

제목에 '문자열 참조'가'변수 이름 '으로 변환됩니다. 문자열 참조로 문자열 배열을 참조하고 있습니까? 코드는 'Transpose'를 통해 시트에 배열을 출력하는 것입니다. 문제를 설명해 주시겠습니까? – bonCodigo

+0

의견을 보내 주셔서 감사합니다. 위의 두 가지 코드 인 "하위 작업"과 "하위 not_working"이 있습니다. "작업 중"프로 시저의 코드는 출력 변수 (cat 및 bat)가 코드에 하드 코딩 된 것을 제외하고는 문제가 없습니다. 나는 "not_working"프로 시저에서했던 것처럼 출력 변수를 참조하고자합니다.출력 변수의 이름은 문자열 참조라고 할 수 있습니다. 내 문제는 내가 참조하는 배열 변수라는 것을 코드가 이해하도록 만드는 것입니다 ... – user1927820

+0

저는 제가 어려움을 겪을 때 가장 어려운 질문 이었기 때문에 bonCodigo의 혼란을 나누었습니다. 당신은 우리가 원하는 기술을 말하고 있습니다. 당신은 왜 우리가 그 기술을 사용하고 싶은지를 말하지 않습니다. 워크 시트에 매개 변수를 저장하여 내 프로그램에서 오늘이 데이터를 여기에 옮기길 원합니다. 두 버전 모두에서 두 개의 배열을 하드 코딩합니다. 목적지 만 다를뿐입니다. 세 번째와 네 번째 배열을 추가 할 예정입니까? 미래의 요구 사항은 무엇입니까? –

답변

-1

귀하의 요구 사항을 올바르게 이해하면 불규칙한 배열이이를 충족시킬 것입니다.

Variant 유형의 변수가있는 경우 해당 변수를 정수, 실수, 문자열, 부울 또는 배열로 설정할 수 있습니다.

Variant 유형의 배열이있는 경우 해당 배열의 각 요소를 다른 유형의 값으로 설정할 수 있습니다.

아래 코드는 변형 배열 Main입니다. I 세트 :

1 차원 배열
  • 메인 (0)
  • 메인 (1) 큰 1D 배열,
  • 주 (2) 2 차원 어레이,
  • 주 (3)
  • 워크 시트의 사용 된 범위에 대한 주 (4).

각 요소의 크기가 다르기 때문에이를 비정형 배열이라고합니다.

배열에 값을로드 한 후, 본질에 따라 Main의 각 요소를 출력하는 일반 루틴을 사용합니다.

각 200-300 개의 변수는 Main의 요소가됩니다.

내 코드를 살펴보십시오. 이것은 변형 배열로 얻을 수있는 것에 대한 간략한 소개 일뿐입니다. 내가 올바른 방향으로 가고 있다고 생각하지만 충분히 멀리 가지 않았다면 질문으로 돌아 가라. 날짜는 "27/12/2012"로 표시됩니다

Option Explicit 
Sub DemoRaggedArray() 

    Dim InxDim As Long 
    Dim InxMain As Long 
    Dim InxWCol As Long 
    Dim InxWRow As Long 
    Dim Main() As Variant 
    Dim NumOfDim As Long 
    Dim Work() As Variant 

    ReDim Main(0 To 5) 

    Work = Array(1, "A", True) 

    Main(0) = Work 

    Main(1) = Array(2, "B", False, 1.2) 

    ReDim Work(1 To 2, 1 To 3) 

    Work(1, 1) = 1 
    Work(1, 2) = 2.5 
    Work(1, 3) = DateSerial(2012, 12, 27) 
    Work(2, 1) = True 
    Work(2, 2) = "String" 

    Main(2) = Work 

    Main(3) = 27 

    ' Cells A1:C4 of the worksheet have been set to their addresses 
    Main(4) = WorksheetFunction.Transpose(Worksheets("Sheet2").UsedRange.Value) 

    For InxMain = LBound(Main) To UBound(Main) 
    Debug.Print "Type of Main(" & InxMain & ") is " & VarTypeName(Main(InxMain)) 
    Select Case VarType(Main(InxMain)) 
     Case vbEmpty, vbNull 
     ' No value 
     Case Is >= vbArray 
     ' Array 
     NumOfDim = NumDim(Main(InxMain)) 
     Debug.Print " Main(" & InxMain & ") is dimensioned as: ("; 
     For InxDim = 1 To NumOfDim 
      Debug.Print LBound(Main(InxMain), InxDim) & " To " & _ 
                UBound(Main(InxMain), InxDim); 
      If InxDim < NumOfDim Then 
      Debug.Print ", "; 
      End If 
     Next 
     Debug.Print ")" 
     Select Case NumOfDim 
      Case 1 
      For InxWCol = LBound(Main(InxMain)) To UBound(Main(InxMain)) 
       Debug.Print " (" & InxWCol & ")[" & _ 
             VarTypeName(Main(InxMain)(InxWCol)) & "]"; 
       Select Case VarType(Main(InxMain)(InxWCol)) 
       Case vbEmpty, vbNull, vbArray 
        ' No code to handle these types 
       Case Else 
        Debug.Print "=" & Main(InxMain)(InxWCol); 
       End Select 
      Next 
      Debug.Print 
      Case 2 
      For InxWRow = LBound(Main(InxMain), 2) To UBound(Main(InxMain), 2) 
       For InxWCol = LBound(Main(InxMain), 1) To UBound(Main(InxMain), 1) 

       Debug.Print " (" & InxWCol & "," & InxWRow & ")[" & _ 
          VarTypeName(Main(InxMain)(InxWCol, InxWRow)) & "]"; 
       Select Case VarType(Main(InxMain)(InxWCol, InxWRow)) 
        Case vbEmpty, vbNull, vbArray 
        ' No code to handle these types 
        Case Else 
        Debug.Print "=" & Main(InxMain)(InxWCol, InxWRow); 
       End Select 
       Next 
       Debug.Print 
      Next 
      Case Else 
      Debug.Print " There is no display code for this number of dimensions" 
     End Select 
     Case Else 
     ' Single variable 
     Debug.Print " Value = " & Main(InxMain) 
    End Select 
    Next 

End Sub 
Public Function NumDim(ParamArray TestArray() As Variant) As Integer 

    ' Returns the number of dimensions of TestArray. 

    ' If there is an official way of determining the number of dimensions, I cannot find it. 

    ' This routine tests for dimension 1, 2, 3 and so on until it get a failure. 
    ' By trapping that failure it can determine the last test that did not fail. 

    ' Coded June 2010. Documentation added July 2010. 

    ' * TestArray() is a ParamArray because it allows the passing of arrays of any type. 
    ' * The array to be tested in not TestArray but TestArray(LBound(TestArray)). 
    ' * The routine does not validate that TestArray(LBound(TestArray)) is an array. If 
    ' it is not an array, the routine return 0. 
    ' * The routine does not check for more than one parameter. If the call was 
    ' NumDim(MyArray1, MyArray2), it would ignore MyArray2. 

    Dim TestDim     As Integer 
    Dim TestResult    As Integer 

    On Error GoTo Finish 

    TestDim = 1 
    Do While True 
    TestResult = LBound(TestArray(LBound(TestArray)), TestDim) 
    TestDim = TestDim + 1 
    Loop 

Finish: 

    NumDim = TestDim - 1 

End Function 
Function VarTypeName(Var As Variant) 

    Dim Name As String 
    Dim TypeOfVar As Long 

    TypeOfVar = VarType(Var) 

    If TypeOfVar >= vbArray Then 
    Name = "Array of type " 
    TypeOfVar = TypeOfVar - vbArray 
    Else 
    Name = "" 
    End If 

    Select Case TypeOfVar 
    Case vbEmpty 
     Name = Name & "Uninitialised" 
    Case vbNull 
     Name = Name & "Contains no valid data" 
    Case vbInteger 
     Name = Name & "Integer" 
    Case vbLong 
     Name = Name & "Long integer" 
    Case vbSingle 
     Name = Name & "Single-precision floating-point number" 
    Case vbDouble 
     Name = Name & "Double-precision floating-point number" 
    Case vbCurrency 
     Name = Name & "Currency" 
    Case vbDate 
     Name = Name & "Date" 
    Case vbString 
     Name = Name & "String" 
    Case vbObject 
     Name = Name & "Object" 
    Case vbError 
     Name = Name & "Error" 
    Case vbBoolean 
     Name = Name & "Boolean" 
    Case vbVariant 
     Name = Name & "Variant" 
    Case vbDataObject 
     Name = Name & "Data access object" 
    Case vbDecimal 
     Name = Name & "Decimal" 
    Case vbByte 
     Name = Name & "Byte" 
    Case vbUserDefinedType 
     Name = Name & "Variants that contain user-defined types" 
    Case Else 
     Name = Name & "Unknown type " & TypeOfVar 
    End Select 

    VarTypeName = Name 

End Function 

출력 에서 DemoRaggedArray

Type of Main(0) is Array of type Variant 
    Main(0) is dimensioned as: (0 To 2) 
    (0)[Integer]=1 (1)[String]=A (2)[Boolean]=True 
Type of Main(1) is Array of type Variant 
    Main(1) is dimensioned as: (0 To 3) 
    (0)[Integer]=2 (1)[String]=B (2)[Boolean]=False (3)[Double-precision floating-point number]=1.2 
Type of Main(2) is Array of type Variant 
    Main(2) is dimensioned as: (1 To 2, 1 To 3) 
    (1,1)[Integer]=1 (2,1)[Boolean]=True 
    (1,2)[Double-precision floating-point number]=2.5 (2,2)[String]=String 
    (1,3)[Date]=27/12/2012 (2,3)[Uninitialised] 
Type of Main(3) is Integer 
    Value = 27 
Type of Main(4) is Array of type Variant 
    Main(4) is dimensioned as: (1 To 3, 1 To 4) 
    (1,1)[String]=A1 (2,1)[String]=B1 (3,1)[String]=C1 
    (1,2)[String]=A2 (2,2)[String]=B2 (3,2)[String]=C2 
    (1,3)[String]=A3 (2,3)[String]=B3 (3,3)[String]=C3 
    (1,4)[String]=A4 (2,4)[String]=B4 (3,4)[String]=C4 
Type of Main(5) is Uninitialised 

하는 것으로 우리 나라의 기본 날짜 형식이기 때문이다. 이 코드를 실행하면 해당 국가의 기본 형식으로 표시됩니다.

관련 문제