0

我目前遇到的问题是尝试编写一个子程序,该子程序将从一个工作表中复制单元格,例如 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

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

4

1 回答 1

2

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”,正如我在上面的代码中所反映的那样

于 2012-10-23T14:43:31.957 回答