简体   繁体   中英

Excel VBA, Get data from Msgbox into a worksheet cell

I am reading a small amount of data from worksheet cells. I can see the data displayed in multiple Msgbox's. The data is there ok. When I try to get the Msgbox to enter this data into separate worksheet cells, it puts them all into one cell, overwriting each previous entry, OR using other code it just enters the last piece of data into multiple cells.

It should be something very simple to do?

Can you please show me how to get Msgbox data into worksheet cells?

Sub Macro3()
    Dim myLastRow As Variant
    Dim myRow As Integer
    Dim myFind As String
    Dim myMatch As String
    Dim myReplace As Variant
    Dim cell, myColumn As Range
    Dim arr() As Variant

    Sheets("Test").Select
    arr = Range("D2:D6")
    For Each myReplace In arr
    'MsgBox "" & myReplace

    Range("A2:A40").Select
    Set myColumn = Cells.Find(myReplace, After:=Range("A1"), LookAt:=xlWhole, SearchOrder:=xlByColumns)
    'MsgBox "" & myColumn
    'MsgBox "" & myColumn.Address
    myFind = myColumn.Offset(0, 1)
    MsgBox "" & myFind

     Range("E2").Value = myFind


    Next

End Sub

In your code, when it says MsgBox... , you are telling Excel to show a message box with certain information (eg myFind). If you want the information in the sheet (or any sheet), you need to replace MsgBox... with a Range() clause. This is very basic VBA so any tutorial should get you there.

Please try the below Code:

Sub Macro3()
    Dim myLastRow As Variant
    Dim myRow As Integer
    Dim myFind As String
    Dim myMatch As String
    Dim myReplace As Range
    Dim cell As Range
    Dim myColumn As Range
    Dim arr As Range
    Dim i As Integer

    i = 2

    Sheets("Test").Select
    Set arr = Range("D2:D6")
    For Each myReplace In arr
    'MsgBox "" & myReplace

    Range("A2:A40").Select
    Set myColumn = Cells.Find(myReplace.Value, After:=Range("A1"), LookAt:=xlWhole, SearchOrder:=xlByColumns)
    'MsgBox "" & myColumn
    'MsgBox "" & myColumn.Address
    myFind = myColumn.Offset(0, 1).Value


     If myFind <> "" Then

    MsgBox "" & myFind

     Cells(i, 5).Value = myFind

     i = i + 1
     End If

    Next
End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM