使用VBA将值分配给单元格

时间:2018-07-08 16:45:32

标签: excel-vba vba excel

我正在尝试将包含字符串“ Senast”的单元格之后的单元格的值放入单元格Q2中。下面的代码不起作用。有什么想法吗?

Sub Find_Data()

    Dim item_in_review As Variant
    Dim row_number As Long

    For row_number = 1 To 1000 Step 1
        item_in_review = Sheets("Investor_Importerad data").Range("A" & row_number)
        If InStr(item_in_review, "Senast") Then
            row_number = row_number + 1
            Worksheets("Översikt innehavCells").Cells(2, "Q").Value = Worksheets("Investor_Importerad data").Cells(row_number, "A").Value
            Exit For
        End If

        If item_in_review = 300 Then
            MsgBox "300"
            Exit For
        End If
    Next row_number

End Sub

1 个答案:

答案 0 :(得分:0)

似乎您正在寻找通配符匹配 Senast 或数字300作为真实数字。以先到者为准,您退出For ... Next循环。

下面充斥着许多错误陷阱和标准条件,这些条件和条件可以隔离您的问题。

Sub Find_Data()

    Dim rSenast As Variant, r300 As Variant, wsn As String

    wsn = "Översikt innehavCells"
    Dim row_number As Long

    With Worksheets("Investor_Importerad data")
        rSenast = Application.Match("*senast*", .Range("a:a"), 0)
        r300 = Application.Match(300, .Range("a:a"), 0)
        If IsError(r300) Then _
            r300 = Application.Match(Format(300, "0"), .Range("a:a"), 0)

        Select Case True
            Case CBool(IsNumeric(rSenast) And IsNumeric(r300))
                If r300 < rSenast Then
                    If MsgBox("300 found before 'senast" & vbLf & "Continue with value transfer?", vbYesNo, "Continue?") <> vbYes Then _
                        Exit Sub
                End If
            Case CBool(IsError(rSenast) And IsError(r300))
                MsgBox "Neither 'senast' nor 300 can be found"
                Exit Sub
            Case CBool(IsError(rSenast) And IsNumeric(r300))
                MsgBox "300 can be found at row " & r300
                Exit Sub
        End Select

        On Error GoTo No_Such_Worksheet
        If .Cells(rSenast + 1, "A").Value <> vbNullString Then
            Worksheets(wsn).Cells(2, "Q") = .Cells(rSenast + 1, "A").Value
        Else
            MsgBox .Cells(rSenast + 1, "A").Address(0, 0) & " appears to be empty"
        End If
        On Error GoTo 0

    End With

    Exit Sub

No_Such_Worksheet:
    With Worksheets.Add(after:=Worksheets("Investor_Importerad data"))
        .Name = wsn
    End With
    Resume

End Sub