2015-07-10 140 views
0

这是第一次使用Excel与VBA一起工作。我正在练习使用公式并使用Excel单元格和MsgBoxes显示值。使用Excel的每行的MsgBox循环Visual Basic

我目前的问题很可能是一个简单的修复,但还没有弄清楚。

我要让我MSGBOX显示每行被填充后如下:

味精弹出

Socks Gross Sale is 56.37 

味精弹出

Lotion Gross Sale is 59.12 
..etc 

然而,当我第一次尝试运行我注释掉的代码行MsgBox Range("A14:A21").Value & " Gross Sale is " & Range("F14:F21").Value它给出了一个错误Run-time error '13': Type mismatch,所以它不起作用。

因此,到目前为止,我正在使用我的代码行MsgBox Range("A14:A21").Value & " Gross Sale is " & Range("F14:F21").Value ,它只通过循环连续填充Sock行。有什么建议么 ?

For Each Cell In Worksheets("Sheet1").Range("B14:E21").Cells 

    Range("F14:F21").Formula = "=SUM((B14*D14)-((B14*D14)*E14))" 
    'MsgBox Range("A14:A21").Value & " Gross Sale is " & Range("F14:F21").Value 

    'Gives me first line only and makes pop up show twice as many times as (all)total rows 
    MsgBox Range("A14").Value & " Gross Sale is " & Range("F14").Value 

Next 

enter image description here

回答

1

您不能发送至MSGBOX ..它在寻找一个字符串..你需要在每个时间来建立串......我建议是这样的:

For i = 14 To 21 

    MsgBox Range("a" & i).Value & " Gross Sale is " & Range("F" & i).Value 

Next i 

那会循环通过行(又名行)你想...和你想要从拉动值拼接在一起的细胞...

For Each Cell 

遍历每个细胞......也不行..

+0

这真的很接近我希望如何做到这一点(简而言之)这个工作顺利!对此,我真的非常感激。我想一个单独的循环是最好的方法。 – narue1992

+0

是的,这是基础知识,显然是硬编码的“14”和“21”,如果你想要/需要一个更动态的范围,你将必须使用;) – Ditto

+0

没错。慢慢地,但我确定我希望得到这种新的编码语言。刚刚昨天才知道Excel使用了VBA O.o。再次感谢!我必须继续练习 – narue1992

1

您可以使用数组通过两个阵列中的每个元素从您的工作表中保存的值,然后循环使用在每次迭代的索引来产生你以后的消息。

Sub produceMsg() 
    Dim i As Byte 
    Dim arrProductName As Variant 
    Dim arrGrossSale As Variant 
    arrGrossSale = Range("F2:F9").Value 
    arrProductName = Range("A2:A9").Value 

    For i = 1 To UBound(arrGrossSale, 1) 
     MsgBox (arrProductName(i, 1) & " Gross sale is " & arrGrossSale(i, 1)) 
    Next i 
End Sub 

从工作表中填充数组时,不管您是否只为数组提供1维,总是会生成2维数组。这就是为什么我们必须在循环数组时指定第二维为'1'。希望这可以帮助。

+0

这个作品真的很好过。我只选择了@Ditto,因为他更简单,但我喜欢这个名字为每个范围声明。我没有想到这样,所以我很高兴你给我看这个!如果只有我可以“勾选”2个答案 – narue1992

0

在旁边的笔记我马德以下更新,以显示对MSGBOX小数点后两位:

MsgBox Range("a" & i).Value & " Gross Sale is $" & FormatNumber(Round(Range("F" & i).Value, 2), 2) 

我加FormatNumber,因为当我使用Round它删除任何数字,其小数点后第二位是0。随着FormatNumber它保持0

加成@Ditto