2016-12-05 180 views
0

我想从我的电脑中选择一个excel文件并将其插入到数据库中。我有一些代码可以正常工作,但是当我点击取消按钮时,它不会取消它,并且保持与打开按钮一样的工作。VBA按钮不起作用

Sub GetDataFromClosedBook() 
'On Error GoTo myError 
Dim mydata As String 
'data location & range to copy 
mydata = "='C:\Users\IT.int08\Downloads\[close.xls]Sheet1'!$A1:$C1000" '<< change as required 
'link to worksheet 
With ThisWorkbook.Worksheets(1).Range("A1:C1000") '<< change as required 

.Formula = mydata 
'convert formula to text 
.Value = .Value 
Cells.Replace What:="'", Replacement:="", LookAt:=xlPart, SearchOrder:= _ 
     xlByRows, MatchCase:=False, SearchFormat:=False, ReplaceFormat:=False 
Dim conn As New ADODB.Connection 
Dim Counter As String 
Counter = Cells.Item(2, 4) 

Dim IRow As Integer 
IRow = Cells.Item(2, 4) 
IRow = IRow + 1 
Dim rgno, taxpname As String 

     conn.Provider = "sqloledb" 
     'conn.Properties("Prompt") = adPromptAlways 
     conn.Open "Data Source=10.10.1.139;Initial Catalog=time;user id=sa;password=11" 

     Do Until .Cells(IRow, 1) = 0 Or Null 
      rgno = .Cells(IRow, 2) 
      taxpname = .Cells(IRow, 3) 
      Cells.Item(2, 4) = IRow 
     Dim Qu As String 
     If Len(rgno) >= 13 Then 

      Qu = "insert into dbo.rough (NTN_no,CNIC,TAXPAYERNAME) values ('" & "" & "', '" & rgno & "', '" & taxpname & "')" 
      conn.Execute (Qu) 
      ElseIf Len(rgno) < 13 Then 
      Dim asdf As String 
      asdf = "insert into dbo.rough (NTN_no,CNIC,TAXPAYERNAME) values ('" & rgno & "', '" & "" & "', '" & taxpname & "')" 
conn.Execute (asdf) 
End If 
IRow = IRow + 1 

DoEvents  
Loop  
'myError: 
'MsgBox ("record is missing") 
Sheet1.Cells.Clear 

End With 
End Sub 
+0

哪一行的错误? – user1

+0

当提示打开不显示错误它工作,但并点击取消按钮然后将其插入数据库 –

+0

你能告诉我请你所看到的 – user1

回答

0

promt发生在哪里? 通常情况下,你必须告诉机器在“取消”上做什么。像:

If [PROMPT] = vbNullString Then 
    Exit Sub 
End If 
+0

它显示类型不匹配错误 –

+0

线8没有提示发生 –

+0

“.Formula = MYDATA”分配路径变量?在VBA – snibbo