简体   繁体   English

Excel VBA宏:通过引用复制单元格

[英]Excel VBA Macro: Copying cells by reference

I am creating a macro in Excel to copy data from one sheet to another within the same workbook. 我在Excel中创建一个宏,以将数据从一个工作表复制到同一工作簿中的另一个工作表。 Currently, the code operates as so: 目前,代码的运行方式如下:

Dim sourceSheet As Worksheet
Dim destSheet As Worksheet
Dim numCases As Integer
Dim i As Integer

numCases = 10
Set destSheet = ThisWorkbook.Sheets("Raw_Data")
Set sourceSheet = ThisWorkbook.Sheets("Formatted_Data")

For i = 1 To numCases
    destSheet.Cells(i,1).Value = sourceSheet.Cells(1,i).Value
Next

This code works properly in that it copies the value from one sheet to the other and places it in the correct cell. 此代码正常工作,因为它将值从一个工作表复制到另一个工作表并将其放在正确的单元格中。 The issue is that I need the cell to be populated as a reference value back to sheet "Raw_Data". 问题是我需要将单元格作为参考值填充回工作表“Raw_Data”。 In other words, when I select a cell in "Formatted_Data", I need the formula bar to show something like: 'Raw_Data'!C1 but instead all I get is the numerical value. 换句话说,当我在“Formatted_Data”中选择一个单元格时,我需要公式栏来显示类似:'Raw_Data'!C1但是我得到的只是数值。 Is there some way that I can perform a copy, or set a value and maintain the reference?? 有没有办法可以执行复制,或设置值并维护引用?

Thanks, 谢谢,

Barret 巴瑞特

Replace 更换

destSheet.Cells(i,1).Value = sourceSheet.Cells(1,i).Value

With

sourceSheet.Cells(1,i).Formula = "=" & destSheet.Name & "!" & destSheet.Cells(i,1).Address(False,False)

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

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