vba 从 Excel 中的不同工作表获取所选单元格的范围

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3230937/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 11:52:27  来源:igfitidea点击:

Getting the selected cell's range from a different worksheet in Excel

excelvbaexcel-vbaexcel-2003

提问by Jeff

I'm trying to set up Excel so that the cell's value that is selected in the first worksheet is set to the value of a cell that's double clicked in a different worksheet. So far my code looks like this:

我正在尝试设置 Excel,以便将在第一个工作表中选择的单元格的值设置为在不同工作表中双击的单元格的值。到目前为止,我的代码如下所示:

Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)



Dim c As Range

For Each c In Sheet1.Range("M11:M24")
    If IsEmpty(c) Then
        c.Value = Target.Value
        Exit For
    End If
Next c
End Sub

What this does is sets the first empty cell in the range m11:m24 to the contents of the double clicked cell in the other worksheet. What I want though is not a static "M11:M24" range, but instead have the user select a cell in the first worksheet by clicking on it, move to the other worksheet, double click a cell in that worksheet and have the value appear in the selected cell on the first worksheet. I think I could have it so that there is a variable set up to save which cell is selected in the first worksheet and then just access that from the other worksheet. But I'd prefer if there was away built in to Excel to just choose the selected cell.

这样做是将 m11:m24 范围内的第一个空单元格设置为另一个工作表中双击单元格的内容。我想要的不是静态的“M11:M24”范围,而是让用户通过单击在第一个工作表中选择一个单元格,移动到另一个工作表,双击该工作表中的一个单元格并显示值在第一个工作表上的选定单元格中。我想我可以拥有它,以便设置一个变量来保存在第一个工作表中选择的单元格,然后从另一个工作表访问它。但我更希望 Excel 内置了只选择选定的单元格。

Is there a way to get the selected cell/range in Excel?

有没有办法在 Excel 中获取选定的单元格/范围?

采纳答案by Jeff

I solved this easily. The code is:

我很容易地解决了这个问题。代码是:

Sheet1.Activate
ActiveCell.Value = Target.Value

If you want to do a whole selection, try

如果你想做一个完整的选择,试试

Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)

    Sheet1.Activate

    Dim r As Range
    Set r = Selection

    r.Value = Target.Value

End Sub