【问题标题】:How do you copy cell data in a range from one sheet to specific cells in another sheet?如何将一个工作表范围内的单元格数据复制到另一张工作表中的特定单元格?
【发布时间】:2012-10-23 22:49:01
【问题描述】:

我目前遇到的问题是尝试编写一个子程序,该程序将从一个工作表中复制单元格,例如 A1:A10;到另一张具有特定单元格的工作表,如 A1、A2、B1、B2、B3、B5、C1、C2、C4、C5。问题是我无法读取工作表名称和范围值的当前子项。这是代码

'User will be able to copy cell data from one to another.
Public Sub CopyCell(ByVal pv_worksheet_source As Worksheet, _
                    ByVal pv_range_source_cells As Range, _
                    ByVal pv_worksheet_destination As Worksheet, _
                    ByVal pv_range_destination_cells As Range, _
                    ByRef pr_str_error_message As String)

'first the cells are compared for the data that is in them.
If pv_range_source_cells.Cells.Count <> pv_range_destination_cells.Cells.Count Then
     pr_str_error_message = pr_str_error_message & "The cell count " & pv_range_source_cells.Cells.Count & " and " & _
        pv_range_destination_cells.Cells.Count & " do not match. The cells of Initial Optics Input and Output cannot be copied!"
    Exit Sub
End If


Dim source_cells As Range
Dim i As Integer
Dim ArrOut() As String
Dim str_source_worksheet_name As String
Dim str_destination_worksheet_name As String



ArrOut() = Split(pv_range_destination_cells.Address, ",")

i = 0


For Each source_cells In pv_worksheet_source
    pv_worksheet_destination.Range(ArrOut(i)).Value = source_cells.Value
    i = i + 1
Next
End Sub

如您所见,代码假定读取源和目标工作表名称,以及它们的单元格范围以进行复制。存在类型不匹配,而且我无法弄清楚如何在 VBA 中复制数据。这个 sub 必须以模块格式保存,因为它将在整个工作簿中为其他工作表调用。这是在源工作表上调用它的示例....

Private Sub CopyButton_Click()
'User gets data copied over to specific cells
   Dim str_error_message As String
    Call CopyCell(Sheet1, _
                  "A1:A10", _
                  Sheet2, _
                  "B1,B2,B3,C1,C2,C3,C4,D1,D2,D3", _
                  pr_str_error_message:=str_error_message)


End Sub

这是我单击按钮时错误开始的地方。请帮忙,因为我已经处理这个问题好几天了!我真的很喜欢它! :)

【问题讨论】:

  • 您是否尝试过将您选择的数据输入到数组中,然后将它们吐出到新工作表上?
  • 当您调用 Sub 时,您通过输入“A1:A10”将范围作为字符串传递,传递这是一个范围,如 Sheets("Sheet1").Range("A1:A10 ") 它将完美地工作。回到我之前提供给您的How to Answerstackoverflow.com/questions/12915415/…>,以了解这种方式的简单性。

标签: vba excel


【解决方案1】:

ArrOut 应该是一个数组,而不是一个字符串。

变化

    Dim ArrOut as String 

    Dim Arrout as Variant

然后像这样设置数组:

   ArrOut = Split(pv_range_destination_cells, ",")

然后调用“粘贴”

   For Each source_cells In pv_worksheet_source
       for i = lbound(arrout) to ubound(arrout)
          pv_worksheet_destination.Range(ArrOut(i)).Value = source_cells.Value
       next i
   Next

编辑:您还在复制按钮单击中将 pv_destination_cells 设置为字符串,但将其声明为子范围内的范围。如果您要在示例中将其称为字符串,则应将其设置为原始子中的字符串,然后从数组声明中省略“.address”,正如我在上面的代码中所反映的那样

【讨论】:

  • 数组被正确分类为字符串,因为 Range.Address 属性被传递给它。如果他将范围而不是字符串传递给代码,则代码将按照他编写的方式工作。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多