首页 > 解决方案 > 获取多个单元格的内容以在 msgbox 中打印

问题描述

我有一个电子表格,我正在运行一个宏,在宏的末尾,我希望它获取第 1 行中所有填充单元格的内容(每次运行时填充单元格的数量都会有所不同)并打印这些单元格的内容一起输出到一个 msgbox。

这是我的单子 示例数据

我想要一个框来连接 A - D 列中的数据并像这样显示:4 应用程序和技术,包括以下黄金和白金层:ABC、DEF、GHI、JKL

(请记住,每次运行时,带有文本的列数都会改变。有时只有 A 和 B,其他可能有 300 或更多,这就是我尝试使用范围的原因)

我不知道如何让消息框选择第 1 行中包含内容的所有单元格,然后在消息框中显示该内容。相反,我得到了这个: 消息框输出

这是我的宏:

Sub TLA_2()

' Count the rows and display the message
Dim No_Of_Rows As Integer
No_Of_Rows = Range(Selection, Selection.End(xlDown)).Rows.Count

'MsgBox No_Of_Rows, vbOKOnly, "Total Number of Applications"
        
Range("A1").Select
MsgBox No_Of_Rows & " Applications and Technologies, including the following Gold and Platinum Tiers: " & Range(Selection, Selection.End(xlToRight)).Select

End Sub

我知道我的问题是我在我的范围末尾有那个 .Select 并且我得到“真实”,因为它选择了数据。我无法弄清楚的是如何让它产生该选择的价值,而不是仅仅确认选择的发生。

我也尝试过使用变量概念,但没有奏效:

Range("A1").Select
Dim paragraph As Object
paragraph = Range(Selection, Selection.End(xlToRight)).Text
MsgBox No_Of_Rows & " Applications and Technologies, including the following Gold and Platinum Tiers: " & paragraph

我知道这将是一个非常愚蠢的新手,但我被困住了!

标签: excelvbamsgbox

解决方案


如果我了解您的设置,您将需要 1 以下行中的数据才能使用 xlEndDown!您还需要第 1 行的动态范围名称,如下所示:

MsgBox =OFFSET(Sheet1!$A$1,0,0,COUNTA(Sheet1!$A$1:$A$1),1000)

Note: this allows for 1000 columns max of premium tiers, adjust as necessary.

如果您选择包含行数据中第一项的单元格,则此代码将起作用,在示例 A2 中。

Option Explicit

Sub DisplayResults()

  Dim No_Of_Rows As Integer
  Dim BaseMsg    As String
  Dim Tiers      As String
  Dim Cell       As Range
  
  BaseMsg = " Applications and Technologies, including the following Gold and Platinum Tier:"
  
  No_Of_Rows = Range(Selection, Selection.End(xlDown)).Rows.Count

  For Each Cell In Range("MsgData")
    Tiers = Tiers & Cell.Value
  Next Cell
  
  MsgBox No_Of_Rows & BaseMsg & vbCrLf & Tiers, vbOKOnly, "Results:"
  
End Sub 'DisplayResults

在此处输入图像描述

高温高压


推荐阅读