在VBA中使用名称的索引匹配函数出错

在VBA中使用名称的索引匹配函数出错,vba,excel,excel-formula,Vba,Excel,Excel Formula,请使用下面的代码帮助我在粗体代码行中发现错误: 更新 所有代码: Private Sub CommandButton2_Click() 'save Dim sname As String Dim yrow As Long, ws As Worksheet sname = ComboBox1.Value Set ws = Sheets(sname) yrow = ws.Range("A" & Rows.Count).End(xlUp).Row + 1

请使用下面的代码帮助我在粗体代码行中发现错误:

更新 所有代码:

Private Sub CommandButton2_Click() 'save
    Dim sname As String
    Dim yrow As Long, ws As Worksheet
    sname = ComboBox1.Value
    Set ws = Sheets(sname)
    yrow = ws.Range("A" & Rows.Count).End(xlUp).Row + 1
If (ComboBox1.Value = "DP" Or ComboBox1.Value = "WD") Then
    If (ComboBox7 = "" Or TextBox1 = "") Then
        MsgBox ("Masih ada kolom yg belum di isi")
        Exit Sub
    Else
        ws.Range("A" & yrow).Value = "=ROW()-1"
        ws.Range("B" & yrow).Value = Sheets("TRX").Range("B2")
        ws.Range("C" & yrow).Value = ComboBox7
        ws.Range("D" & yrow).Value = TextBox1.Value
    End If
End If
If (ComboBox1.Value = "BELI") Then
    If (ComboBox3 = "" Or ComboBox5 = "" Or ComboBox6 = "") Then
        MsgBox ("Masih ada kolom yg belum di isi")
        Exit Sub
    Else
        ws.Range("A" & yrow).Value = "=ROW()-1"
        ws.Range("B" & yrow).Value = Sheets("TRX").Range("B2")
        ws.Range("C" & yrow).Value = ComboBox3
        **ws.Range("D" & yrow).Value = Application.WorksheetFunction.Index(harga, Application.WorksheetFunction.Match(ComboBox3, koin, 0)).Value**
    End If
End If

End Sub

谢谢你的回复

在一个新的Excel文件上,用F8逐步运行这段代码:

Option Explicit

Public Sub TestMe()

    Dim ws As Worksheet: Set ws = Worksheets(1)
    Dim harga As Range: Set harga = ws.Range("A1:C10")
    Dim comboBox3 As String
    Dim koin As Range: Set koin = ws.Range("D1:D10")

    comboBox3 = "Something"
    Range("D3") = "Something"
    Range("A3") = "Something"

    With WorksheetFunction
        Debug.Print .Match(comboBox3, koin, 0)
        ws.Range("D5") = .Index(harga, .Match(comboBox3, koin, 0), 1)
    End With

End Sub
它显示了如何使用匹配和索引。在所讨论的代码中,可能没有匹配项,因此会导致错误。如果希望返回错误而不是抛出错误,请尝试Application.Match和Application.Index:


你确定比赛后你没有遗漏任何论点吗?我查回来,没有逃避。我不知道这个错误在哪里。谢谢你的比较。这对我来说越来越难了,因为与前面的代码相差太远了
Public Sub TestMe()

    Dim ws As Worksheet: Set ws = Worksheets(1)
    Dim harga As Range: Set harga = ws.Range("A1:C10")
    Dim comboBox3 As String
    Dim koin As Range: Set koin = ws.Range("D1:D10")

'    comboBox3 = "Something"
'    Range("D3") = "Something"
'    Range("A3") = "Something"

    With Application
        Debug.Print .Match(comboBox3, koin, 0)
        ws.Range("D5") = .Index(harga, .Match(comboBox3, koin, 0), 1)
    End With

End Sub