[英]How do you copy cell data in a range from one sheet to specific cells in another sheet?
我目前遇到的問題是嘗試編寫一個子程序,它將從一個工作表中復制單元格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
這是我單擊按鈕時錯誤開始的地方。 請幫助,因為我已經處理這個問題好幾天了! 我真的很滿意! :)
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”,因為我已在上面的代碼中反映出來了
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.