简体   繁体   中英

Getting Excel Vba Runtime Error 1004

Private Sub CommandButton3_Click()
    Dim rownum, startcol, endcol, holder As Integer
    rownum = InputBox("Enter the row that swapping process going to happen")
    startcol = InputBox("Enter the column of the cell you want to swap")
    endcol = InputBox("Enter the column of the cell that you wanted swap with")
    holder = Cells(rownum, startcol).Value
    Cells(rownum, startcol).Value = Cells(rownum, endcol).Value
    Cells(rownum, endcol).Value = holder
End Sub

Gives

Runtime Error 1004 - "Run-time error '1004': Application-defined or object-defined error"

Can't seem to understand.

Dim your vars properly and use application.inputbox for more options.

'using column numbers
Private Sub CommandButton3_Click()
    Dim rownum as long, startcol as long, endcol as long, holder As variant
    rownum = application.InputBox("Enter the row that swapping process going to happen", type:=1)
    startcol = application.InputBox("Enter the column number of the cell you want to swap", type:=1)
    endcol = application.InputBox("Enter the column numbedr of the cell that you wanted swap with", type:=1)
    holder = Cells(rownum, startcol).Value
    Cells(rownum, startcol).Value = Cells(rownum, endcol).Value
    Cells(rownum, endcol).Value = holder
End Sub

'using column letters
Private Sub CommandButton3_Click()
    Dim rownum as long, startcol as string, endcol as string, holder As variant
    rownum = application.InputBox("Enter the row that swapping process going to happen", type:=1)
    startcol = application.InputBox("Enter the column letter of the cell you want to swap", type:=2)
    endcol = application.InputBox("Enter the column letter of the cell that you wanted swap with", type:=2)
    holder = Cells(rownum, startcol).Value
    Cells(rownum, startcol).Value = Cells(rownum, endcol).Value
    Cells(rownum, endcol).Value = holder
End Sub

The type:=1 tells application.inputbox to expect a number; type:=2 tells application.inputbox to expect a string.

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