使用单元格值在Excel VBA中指定粘贴位置

时间:2014-02-04 22:54:40

标签: excel vba excel-vba

我有一个包含两行的表:第一行包含应粘贴第二行值的位置。

例如:

row 1 : sheet8!D2  sheet6!D2   sheet2!C5
row 2 : apple      lemon       pEER

所以应该将苹果粘贴在8号细胞D8中。柠檬应粘贴在sheet6细胞D2中。问题是苹果值粘贴在任何地方(sheet8!D2sheet6!D2sheet2!C5)。我怎么能纠正这个?

Sub Sample()
Dim rng As Range
Dim Sh As String, Cl As String
Dim ws As Worksheet
Dim i As Integer
Dim Row1 As String

ncol = Range("A1:F1").Columns.Count

For i = 1 To ncol


Row1 = Range("A1:F1").Cells(1, i).Value

Set ws = ThisWorkbook.Sheets("Sheet2")

With ws
    Sh = Split(Row1, "!")(0)
    Cl = Split(Row1, "!")(1)

    Set rng = ThisWorkbook.Sheets(Sh).Range(Cl)

    rng.Value = .Range("A2").Value

End With

Next i

End Sub

1 个答案:

答案 0 :(得分:2)

您的代码存在一些问题。首先,将Option Explicit置于每个模块的顶部,这将确保定义变量(ncol未定义)。

以下代码将解决问题,尽管可以通过各种方式进行调整。主要问题是您没有正确设置引用范围,您使用循环遍历列但始终返回单元格A2。假设您的输入数据位于第1行和第2行,并从包含该数据的工作表中运行,这将起作用。

Sub SampleFixed()
    Dim rng As Range
    Dim Sh As String, Cl As String
    Dim ws As Worksheet
    Dim i As Integer, ncol As Integer
    Dim Row1 As String

    ncol = Range("A1:F1").Columns.Count

    For i = 1 To ncol
        Set ws = ActiveSheet

        With ws
            Row1 = .Cells(1, i).Value

            If Len(Row1) > 0 Then
                Sh = Split(Row1, "!")(0)
                Cl = Split(Row1, "!")(1)
                Set rng = ThisWorkbook.Sheets(Sh).Range(Cl)

                'Here you were always refering to cell A2 not moving through the values which was the main problem.
                rng.Value = .Cells(2, i).Value     
            End If
        End With
    Next i
End Sub