我目前遇到的问题是尝试编写一个子程序,它将从一个工作表中复制单元格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中复制数据。此子必须保留为模块格式,因为它将在整个工作簿中为其他工作表调用。以下是在源工作表上调用它的示例....
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
这是我单击按钮时错误开始的地方。请帮助,因为我已经处理这个问题好几天了!我真的很满意! :)
答案 0 :(得分: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设置为调用中的字符串,但将其声明为sub中的范围。你应该把它设置为原始子中的字符串,如果你打算像你的例子中那样将它称为字符串,然后从数组声明中省略“.address”,因为我已在上面的代码中反映