vba VBA如何从选定的单元格中获取值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41132329/
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
VBA How to get values from selected cells
提问by Yszty
I need put data from selected cells to array. How to do it? I cant find any example. I know how to get value from one cell by ActiveCell.Valuebut how its work with multiple selection. Guess I should selected range put to variable as object and process it by foreach loop. Can anyone write example for it?
我需要将选定单元格中的数据放入数组。怎么做?我找不到任何例子。我知道如何从一个单元格中获取价值,ActiveCell.Value但它如何与多项选择一起工作。猜猜我应该选择范围作为对象放入变量并通过 foreach 循环处理它。任何人都可以为它写例子吗?
Solution:
解决方案:
Sub Button1_Click()
For Each OneCell In Selection
MsgBox (OneCell.Value)
Next
End Sub
回答by Slai
Application.Selectionis not always Range(for example if Shape(s) or ActiveX Control(s) are selected), and Selection.Valuereturns different things depending on what is selected:
Application.Selection并不总是Range(例如,如果选择了 Shape(s) 或 ActiveX Control(s)),并Selection.Value根据选择的内容返回不同的内容:
- cell value if only one cell is selected
- 2D Variant array of cell values if more than one cell is selected
- error if the object(s) selected don't have a
.Valueproperty
- 如果仅选择一个单元格,则单元格值
- 如果选择了多个单元格,则为单元格值的二维变体数组
- 如果所选对象没有
.Value属性,则出错
If more than one area is selected, .Valuereturns the value(s) only of the first area.
如果选择了多个区域,则.Value仅返回第一个区域的值。
If TypeOf Selection Is Excel.Range Then
Debug.Print Selection.Address(0, 0)
For Each area In Selection.Areas
Debug.Print area.Address(0, 0)
Next
Else
Debug.Print TypeName(Selection)
End If
The Localswindow can make it easier to see the contents of the Application.Selection
在当地人的窗口可以更容易看到的内容Application.Selection
回答by Navin
You don't have to use OneCell.Valueas the cell itself holds the value.
If you want to get the cells formula then use OneCell.FormulaR1C1.
您不必使用,OneCell.Value因为单元格本身包含该值。如果要获取单元格公式,请使用OneCell.FormulaR1C1.
For Each OneCell In Selection
MsgBox (OneCell)
Next OneCell

