PDA

View Full Version : [VBA] How can I loop through the value of selected cells in a table?



smallxyz
09-02-2018, 04:32 AM
I want to get msgbox the value of selected cells in a table.
Any hint how to do it?
Thanks.


Dim Cell As Range
For Each Cell In Selection.Cells
MsgBox Cell.Cells.Value
Next


Failed attempt. Thanks.

gmayor
09-02-2018, 05:04 AM
You need


Dim oCell As Cell
Dim oRng As Range
For Each oCell In Selection.Cells
Set oRng = oCell.Range 'Set a range to the cell
oRng.End = oRng.End - 1 'remove the cell end character from the range
MsgBox oRng.Text 'report the content
Next oCell

smallxyz
09-02-2018, 05:47 AM
:bow::bow::bow:

gmaxey
09-02-2018, 06:37 AM
I you want it reduced to a single message box:


Sub ReturnCellText()
Dim strText As String
strText = Replace(Selection.Range.Text, Chr(13) & Chr(7) & Chr(13) & Chr(7), Chr(13) & Chr(7))
MsgBox Join(Split(strText, Chr(13) & Chr(7)), vbCr)
lbl_Exit:
Exit Sub
End Sub

macropod
09-02-2018, 02:57 PM
Simpler, if there are no paragraph breaks in the cells:


Dim Cell As Range
For Each Cell In Selection.Cells
MsgBox Split(Cell.Range.Text, vbCr)(0)
Next
This could be accumulated to a single output, too.

gmaxey
09-03-2018, 11:00 AM
Likewise simpler even if there are paragraph breaks in the cells:


Dim Cell As Cell
For Each Cell In Selection.Cells
MsgBox Split(Cell.Range.Text, Chr(7))(0)
Next
lbl_Exit:
Exit Sub

Paul, did mean Dim oCell as Cell? As is, your code errors on the msgbox line.

macropod
09-03-2018, 02:12 PM
Paul, did mean Dim oCell as Cell? As is, your code errors on the msgbox line.
I simply modified the OP's code without paying too much attention to how the variables had been declared. I agree, though, that reserved names should not be used that way.