在单元格中输入值,而不是从剪贴板粘贴

时间:2018-12-22 14:59:14

标签: excel vba

我有一个Excel宏(主文件),它将打开另一个工作簿(数据源),并且应该将某些行中的数据粘贴到当前工作簿(主文件)中。

在按Button1之前,宏将我复制的内容(存储在我认为的剪贴板中)粘贴到我选择的单元格中是有问题的。我试图清除剪贴板,但没用。

Option Explicit

Sub Button1_Click()

Application.ScreenUpdating = False

Dim last_row, i, j As Long
Dim wo_num As String

'open data source

Dim data_source As Workbook
Dim destination As Workbook

Set destination = ThisWorkbook
Set data_source = Workbooks.Open("xxxxxxxxxxxxxxxxxxxxxxxx", True, True)
Application.DisplayAlerts = False


'refresh data source connection to database
'data_source.RefreshAll

last_row = data_source.Worksheets(3).Cells(Rows.Count, 1).End(xlUp).Row

wo_num = "0000057305"
j = 1

'search for the cell that match wo_num and copy entire row then paste on main file
For i = 2 To last_row
    If data_source.Worksheets(3).Cells(i, 1) = wo_num Then
        'data_source.Worksheets(3).Rows(i).EntireRow.Copy
        destination.Worksheets(1).Rows(j).Value = data_source.Worksheets(3).Rows(i).Value
        destination.Worksheets(1).Paste
        j = j + 1
    End If
Next i

data_source.Close False

Application.ScreenUpdating = True

'clear the clipboard
Application.CutCopyMode = False

MsgBox "Done!"

End Sub

我的屏幕上发生了什么
What happened on my screen

单元格包含“ destination.Worksheets(1).Cells(1,26).Select”是我刚刚按Ctrl + C的代码行。

1 个答案:

答案 0 :(得分:0)

您正在使用基于复制数据的数组,无需使用paste,因为您没有将任何内容复制到剪贴板。 只需删除该行或将其添加为注释,只需在该行的第一行添加'REM即可,就像您对wholerow.copy行;-)所做的一样。

 For i = 2 To last_row
    If data_source.Worksheets(3).Cells(i, 1) = wo_num Then
        'data_source.Worksheets(3).Rows(i).EntireRow.Copy
        destination.Worksheets(1).Rows(j).Value = data_source.Worksheets(3).Rows(i).Value
        ' destination.Worksheets(1).Paste !! run your code without this line and see what is happening. 
        j = j + 1
    End If
Next i

希望这可以解决您的问题。否则,我们需要知道何时将某些内容复制到剪贴板中。 如果您在工作表的所有16384列中均没有真正的价值,则另一条注释可能不会转移所有行。使用cells(i,1).resize(,numberof columns)使您的代码更加敏捷。

      destination.Worksheets(1).cells(j,1).resize(,NumberofColumns).Value = data_source.Worksheets(3).cells(i,1).resize(,NumberofColumns).Value

反正很好,

致谢,
M