2017-10-06 10 views
0

매크로가 데이터베이스 테이블의 데이터를 가져 오는 Excel 2010 Workboox에서 작업하고 있습니다. 그런 다음 사용자는 필요한 경우 Column06의 값을 특정 값으로 업데이트 할 수 있습니다. 완료되면 SQL 갱신을 실행하기 위해 매크로를 실행하여 COLUMN01 및 COLUMN02가 데이터베이스 테이블에있는 데이터베이스의 Column06이 갱신됩니다. ADO 연결 잘 작동하는 매우 일반적인 SQL 시도한 것처럼 작동하는지 알 수 있습니다. 테이블의 길이가 다양 할 수 있다는 것을 알고 있으므로 행을 반복 할 필요가 있다는 것을 알았습니다.VBA ListColumns를 사용하여 Excel에서 MS SQL Server 2008로 SQL을 업데이트

온라인에서 찾은 다른 솔루션과 유사한 루프를 설정하고 런타임 오류 91 "개체 변수 또는 블록 변수가 설정되지 않았습니다"가 표시되기 시작했습니다. 나는 새로운 Update Statement에서 사용하고있는 ListObject.ListColumns 때문이라고 생각한다. 나는 이것을 선언하기 위해 다른 예제를 사용해 보았지만 보통 다른 에러로 끝난다. 나는 뭔가를 놓치거나 뭔가 잘못하고 있어야합니다. 어떤 도움이라도 대단히 감사하겠습니다.

Sub Updatetbl_data() 
' 
' Updatetbl_data Macro 
' test 
Sheets("Sheet2").Select 
Dim cnn As ADODB.Connection 
Dim uSQL As String 

Set cnn = New Connection 
    cnnstr = "Provider=SQLOLEDB; " & _ 
    "Data Source=MySource; " & _ 
    "Initial Catalog=MyDB;" & _ 
    "User ID=ID;" & _ 
    "Password=Pass;" & _ 
    "Trusted_Connection=No" 
cnn.Open cnnstr 
' New Update Statement idea based on possible solution found online 
Dim row As Range 
For Each row In [tbl_data].Rows 
uSQL = "UPDATE tbl_data SET Column06 = '" & (row.Columns (row.ListObject.ListColumns("Column06").Index).Value) & _ 
"' WHERE Column01 = '" & (row.Columns(row.ListObject.ListColumns ("Column01").Index).Value) & _ 
"' AND Column02 = '" & (row.Columns(row.ListObject.ListColumns("Column02").Index).Value) & "' " 
'Debug.Print (uSQL) 
cnn.Execute uSQL 
Next 

cnn.Close 
Set cnn = Nothing 
Exit Sub 

' 
End Sub 

답변

0

아마도 row.Columns은 달성하려는 목적으로 설계되지 않았습니다. 더 많은 정보를 원하시면 this link to another article on stackoverflow을 찾으십시오. 다음으로, 트릭을 할 수있는 코드를 약간 변경했습니다.


    ' ... ... ... 
    Dim row As Range 
    'For Each row In [tbl_data].Rows ==>> has to be replaced by 
    'For Each row In [tbl_data] ==>> which returns all cells, perhaps better the following 
    Const ColNbr_Column01 As Long = 1 
    Const ColNbr_Column02 As Long = 2 
    Const ColNbr_Column06 As Long = 6 
    ' now, select only the first column of the range [tbl_data] 
    For Each row In Range(_ 
         [tbl_data].Cells(1, 1).Address, _ 
         [tbl_data].Cells([tbl_data].Rows.Count, 1).Address) 

    ' now, use offset to reach to the columns in the row 
    uSQL = "UPDATE tbl_data SET Column06 = '" & row.Offset(0, ColNbr_Column06).Value & _ 
    "' WHERE Column01 = '" & row.Offset(0, ColNbr_Column01).Value & _ 
    "' AND Column02 = '" & row.Offset(0, ColNbr_Column02).Value & "' " 
    'Debug.Print (uSQL) 
    ' ... ... ... 

+0

JonRo, 내가 각각 1 씩 줄 상수를 줄이면, 예를 들어. Col_Nbr__Coumn06 = 5. 이제는 "빈 상태가 아닌 IF를 던지는 방법을 알아야하고, 루프를 빠져 나가야합니다. 나는 가야합니다." – drkevorkiian

+0

마지막 도전을 생각하면, 내가 만든 것보다 쉽습니다. 그것은. I 단지 롱 = 5 '는 이제 각 행에 대한 범위는 [tbl_data] 의 첫 번째 열을 선택만큼 = 1 헌장 ColNbr_Column06만큼 = 0 헌장 ColNbr_Column02로서 코드 약간 헌장 ColNbr_Column01 수정했다[tbl_data] .Cells (1, 1) .Address, _ [tbl_data] .Cells ([tbl_data] .Rows.Count, 1) .Address) 행. 오프셋 (0, 열 01) 인 경우. Value = ""Then Exit for '이제 오프셋을 사용하여 행의 열에 도달합니다. – drkevorkiian

0

이것은 기본 개념입니다.

Sub InsertInto() 

'Declare some variables 
Dim cnn As adodb.Connection 
Dim cmd As adodb.Command 
Dim strSQL As String 

'Create a new Connection object 
Set cnn = New adodb.Connection 

'Set the connection string 
cnn.ConnectionString = "Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=True;Initial Catalog=Database;Data Source=Server_Name" 



'Create a new Command object 
Set cmd = New adodb.Command 

'Open the Connection to the database 
cnn.Open 

'Associate the command with the connection 
cmd.ActiveConnection = cnn 

'Tell the Command we are giving it a bit of SQL to run, not a stored procedure 
cmd.CommandType = adCmdText 

'Create the SQL 
strSQL = "UPDATE TBL SET JOIN_DT = '2017-10-08' WHERE EMPID = 1" 

'Pass the SQL to the Command object 
cmd.CommandText = strSQL 


'Execute the bit of SQL to update the database 
cmd.Execute 

'Close the connection again 
cnn.Close 

'Remove the objects 
Set cmd = Nothing 
Set cnn = Nothing 

End Sub