2015-07-10 42 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