【问题标题】:Using cell value to specify the paste location in Excel VBA使用单元格值指定 Excel VBA 中的粘贴位置
【发布时间】:2014-02-05 07:13:33
【问题描述】:

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

例如:

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

所以苹果应该粘贴在表格 8 单元格 D8 中。柠檬应粘贴在 sheet6 单元格 D2 中。问题是值 apple 被粘贴到任何地方(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

【问题讨论】:

  • @BK210 感谢您编辑我的问题!!

标签: vba excel


【解决方案1】:

您的代码存在一些问题。首先将 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

【讨论】:

  • 同意选项明确
猜你喜欢
  • 2015-11-12
  • 1970-01-01
  • 2017-04-18
  • 2015-02-07
  • 1970-01-01
  • 1970-01-01
  • 2023-04-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多