使用单元格值在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 

你的代码有几个问题。 首先,将Option Explicit放在每个模块的顶部,这将确保variables已定义( ncol未定义)。

下面的代码将解决这个问题,虽然它可以以各种方式进行调整。 主要的问题是你没有正确地设置引用范围,你用循环遍历列,但总是引用回单元格A2。 假设您的input数据在第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