简体   繁体   English

将单元格值从一个工作簿复制到另一个工作簿

[英]Copying cell values from one Workbook into another

I have the following code that I've written to take some names and use them to populate a timesheet. 我编写了以下代码,以使用一些名称,并使用它们来填充时间表。

Sub InitNames()
    Dim i As Integer
    i = 0
    Dim name As String

    Windows("Employee Data.xlsx").Activate
    Sheets("Employees").Select
    Range("A2").Select
    Do Until IsEmpty(ActiveCell)
        name = ActiveCell.Value
        Workbooks("Timesheet").Sheets("ST").Range("A9").Offset(i * 9).Value = name
        ActiveCell.Offset(1, 0).Select
    Loop
End Sub

Basically, the cells in the target sheet are spaced 9 rows away from each other, so the first name would go in cell A9, the second in A18, the third in A27, and so on. 基本上,目标表中的单元格彼此隔开9行,因此第一个名称将出现在单元格A9中,第二个将出现在A18中,第三个将出现在A27中,依此类推。 I'm sure I'm missing something incredibly simple, but I'm not getting any feedback from Excel whatsoever (no error messages). 我确定我缺少了一件非常简单的事情,但是我没有从Excel得到任何反馈(没有错误消息)。 The cells in the timesheet are merged cells, but I cannot change them (locked by the owner), but I don't think that has anything to do with it. 时间表中的单元格是合并的单元格,但是我无法更改它们(由所有者锁定),但是我认为这与它无关。

EDIT : I added a line: OriginalValue = Workbooks("Timesheet").Sheets("ST").Range("A10").Offset((x - 2) * 9, 0).Value so I could watch to see what values were being overwritten in my Timesheet and I noticed something interesting: OriginalValue only grabs the first cell's text (A9), thereafter, for every cell (A18, A27, etc.) the debugger indicates that OriginalValue = "" even though those cells also contain names. 编辑 :我添加了一行: OriginalValue = Workbooks("Timesheet").Sheets("ST").Range("A10").Offset((x - 2) * 9, 0).Value所以我可以看一下时间表中覆盖了哪些值,我注意到了一些有趣的事情:OriginalValue仅捕获第一个单元格的文本(A9),此后,对于每个单元格(A18,A27等),调试器仍会指示OriginalValue =“”,即使这些单元格还包含名称。 However, when I open another worksheet and reference A9, A18, etc., I AM pulling the names. 但是,当我打开另一个工作表并引用A9,A18等时,我正在拉名称。

EDIT 2 : I modified the test line to read Workbooks("Timesheet").Sheets("ST").Range("A" & ((x - 1) * 9)).Value = "Test" which does change the values in all the target cells. 编辑2 :我修改了测试行以读取Workbooks("Timesheet").Sheets("ST").Range("A" & ((x - 1) * 9)).Value = "Test" ,它确实改变了所有目标单元格中​​的值。 Why would VBA allow me to assign "Test" to a cell value but not the names in the other worksheet? 为什么VBA允许我将“测试”分配给单元格值,而不是其他工作表中的名称?

Try something like this. 尝试这样的事情。 It will accomplish the task you are requesting without using .Select or .Activate 它将完成您所请求的任务,而无需使用.Select.Activate

Sub InitNames()
Dim i As Integer
Dim Wksht as Worksheet
i = 0

Set Wksht = Workbooks("Employee Data.xlsx").Sheets("Employees")
For i = 2 to Wksht.Range("A" & Wksht.Rows.Count).End(xlUp).Row
    Workbooks("Timesheet").Sheets("ST").Range("A9").Offset((i-2) * 9,0).Value = Wksht.Range("A" & i).Value
Next i
End Sub

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM