如何在VBA中创建矢量?

时间:2014-06-20 12:24:44

标签: excel vba excel-vba ms-word

我有一个小问题,我需要在EXCEL VBA中创建一个向量。

我有以下情况

str=Sheets("Indata").Range("$C$12")

Vector= str

例如,如果C12中的单元格为11,我想要以下输出:

Vector= "1 2 3 4 5 6 7 8 9 10 11"

3 个答案:

答案 0 :(得分:2)

<强> NUMBERS

  Sub test()
    Dim str As String
    str = Join(Application.Transpose(Evaluate("ROW(A1:A" & Range("C12").Value2 & ")")), " ")
    Debug.Print str
  End Sub

信函

Sub test2()
    Dim str As String, varr, lCnt As Long
    varr = Application.Transpose(Evaluate("64 + ROW(A1:A" & Range("C12").Value2 & ")"))
    For lCnt = LBound(varr, 1) To UBound(varr, 1)
        str = str & " " & Chr(CLng(varr(lCnt)))
    Next lCnt
    Debug.Print str
End Sub

<强>更新

LETTERS 的循环避免:

Sub test3()
     Dim str As String
    Const ALPHABET = "A B C D E F G H I J K L M N O P Q R S T U V W X Y Z"
    str = IIf(CLng(Range("C12").Value2) <= 26, _ 
        Mid(ALPHABET, 1, 1 + (2 *CLng(Range("C12").Value2 - 1))), "Error")
    Debug.Print str
End Sub

您没有指定如果值超过最后一个字母会发生什么,所以我抛出一个错误。这是你想要的吗?

答案 1 :(得分:1)

考虑:

Public Function Vector(rIn As Range) As String
    Dim N As Long
    N = rIn(1).Value
    Vector = "1"
    For i = 2 To N
        Vector = Vector & " " & i
    Next i
End Function

修改#1:

要获得字母向量,请使用:

Public Function VectorA(rIn As Range) As String
    Dim N As Long
    N = rIn(1).Value
    VectorA = "A"
    For i = 2 To N
        VectorA = VectorA & " " & Chr(64 + i)
    Next i
End Function

答案 2 :(得分:0)

<强> ------- SOLUTION -----------

以上是上述问题的解决方案:

Dim N As Long
    N = Sheets("Indata").Range("$C$12").Value
    vector = "1"
    For i = 2 To N
        vector = vector & " " & i
    Next i

它的作用是从 Sheets(&#34; Indata&#34;)得到一个值11。范围(&#34; $ C $ 12&#34;)。值并返回一个矢量:

vector="1 2 3 4 5 6 7 8 9 10 11"

----使用字母代替数字的代码-----

  

Dim M As Long,vectorA As String

     

M =表格(&#34; Indata&#34;)。范​​围(&#34; $ C $ 13&#34;)。值

     

vectorA =加入(评估(&#34;转置(字符(行(65:&#34;&amp; M + 64&amp;&#34;)))&#34;)

它的作用是从 Sheets(&#34; Indata&#34;)得到一个值11。范围(&#34; $ C $ 13&#34;)。值并返回一个矢量:

vector="A B C D E F G H I J K"