如何在VBA中输出指定的值

时间:2017-07-31 02:21:45

标签: vba

有人可以帮助我解决这个非常简单的问题。基本上这是一个简化的代码,用于解决我想要解决的更复杂的问题。我希望能够在b列中输出我分配给a,b,c,d和e的值。我用于a,b,c,d和e的值取自单元格a1,a2,a3,a4和a5。

谢谢:)

Sub help()
    Dim letters As String
    Dim count As Integer

    a = Range("a1").Value
    b = Range("a2").Value
    c = Range("a3").Value
    d = Range("a2").Value
    e = Range("a3").Value

    letters = "abcde"

    For count = 1 To Len(letters)
        Range("b" & count) = Mid(letters, count, 1)
    Next

    'HOW DO I OUTPUT THE ASSIGNED VALUES TO a,b,c,d & e RATHER THAN OUTPUTTING LETTERS?'
End Sub

2 个答案:

答案 0 :(得分:2)

最简单的方法是更改​​代码,如下所示:

Sub help()
    a = Range("a1").Value
    b = Range("a2").Value
    c = Range("a3").Value
    d = Range("a2").Value
    e = Range("a3").Value

    Range("b1").Value = a
    Range("b2").Value = b
    Range("b3").Value = c
    Range("b4").Value = d
    Range("b5").Value = e
End Sub

或者,您可以使用数组而不是单个变量,例如

Sub help()
    Dim myArr(1 To 5) As Variant
    Dim count As Long
    For count = 1 To 5
        myArr(count) = Cells(count, "A").Value
    Next count    

    For count = 1 To 5
        Cells(count, "B").Value = myArr(count)
    Next count    
End Sub

也可以通过说:

来简化
Sub help()
    Dim myArr As Variant
    myArr = Range("A1:A5").Value ' myArr will be a two-dimensional array
    Range("B1:B5").Value = myArr
End Sub

或者,正如John Coleman在评论中建议的那样,你可以使用词典:

Sub help()
    Dim myVars As Object
    Dim letters As String
    Dim count As Long
    Set myVars = CreateObject("Scripting.Dictionary")

    myVars("a") = Range("a1").Value
    myVars("b") = Range("a2").Value
    myVars("c") = Range("a3").Value
    myVars("d") = Range("a2").Value
    myVars("e") = Range("a3").Value

    letters = "abcde"

    For count = 1 To Len(letters)
        Range("b" & count) = myVars(Mid(letters, count, 1))
    Next
End Sub

答案 1 :(得分:1)

只需转动您对变量所做的分配,然后转到单元格。

其他一些快速提示:

  1. 此外,虽然VBA不需要特定的变量声明,但隐式声明的类型始终为Variant。因此,声明所有变量并始终使用Option Explicit
  2. 被视为专业实践
  3. 始终定义和设置对工作簿和工作表的引用。
  4. 因此...

    Sub help()
        Dim wb as Workbook
        Dim ws as Worksheet
        Set wb = ThisWorkbook
        Set ws = wb.Sheets("Sheet1")
    
        Dim a as String
        a = ws.Range("A1")
    
        ws.Range("B1") = a
    End Sub