简体   繁体   中英

How to get the cell value in Excel?

I want to compare my cell value with the textbox in Excel VBA, but what I get is Object defined error. I don't know why? Please help?

Private Sub btnPayment_Click()
    Dim ws As Worksheet
    For Each ws In Excel.Worksheets
        If ws.Name = "Payroll" Then
            Set ws = Worksheets("Payroll")
                For counter = 0 To ws.UsedRange.Rows.Count
                    If ws.Cells(counter, 3).Value = txtStaffCode.Value Then
                        lblStatus.Caption = "Paid"
                    Else
                        i = ws.UsedRange.Rows.Count
                        j = ws.UsedRange.Rows.Count + 1
                         ws.Cells(i + 1, 1).Value = i
                         ws.Cells(i + 1, 2).Value = Format(Now, "[$-409]m/d/yyyy h:mm AM/PM;@")
                         ws.Cells(i + 1, 3).Value = txtStaffCode.Value
                         ws.Cells(i + 1, 4).Value = txtName.Value
                         ws.Cells(i + 1, 5).Value = Val(txtBaseSalary.Text)
                    End If
                Next counter
            Exit For
        End If
    Next
End Sub

If ws.Cells(counter, 3).Value = txtStaffCode.Value Then 'This is the Error line. Please help

尝试: If ws.Cells(counter, 3).Value = Val(txtStaffCode.Text) Then

The cells collection in Excel is 1-based, you are assuming it is 0-based, hence the error. So, counter should start at 1, not 0. Please read https://superuser.com/questions/988321/which-excel-objects-are-zero-based-and-which-are-one-based

Hope this helps

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