[英]VBA matching cell range values to table column name
我有一个包含列的工作表和一个来自数据库的表。 我想将列的每个值与 TABLE 列匹配。 如果 TABLE 列中不存在列值,则系统会询问您是否要添加该列值。 所以,只是某种循环或映射每个值。 非常感谢你的帮助。
我试过的:
Set adocn = New ADODB.Connection
adocn.Open sConnString
Set recset = adocn.Execute("Select * from table1")
Range("A1").Select
Set a = Range(Selection, Selection.End(xlToRight))
For Each col In a
For Each fld In recset.Fields
If fld.Name <> col.Value Then
If MsgBox("Add " & col.Value & " to column?", vbYesNo + vbQuestion) = vbYes Then
aa = "insert into table1 values('" & col.Value & "')"
adocn.Execute aa
End If
Exit For
Exit For
Next
Next
Sub AddMissingValues()
' Declare variables
Dim adocn As ADODB.Connection
Dim recset As ADODB.Recordset
Dim col As Range
Dim fld As Field
' Establish database connection
Set adocn = New ADODB.Connection
adocn.Open sConnString
' Retrieve data from table1
Set recset = adocn.Execute("Select * from table1")
' Select the first cell in column A
Range("A1").Select
' Set the range to be the entire column
Set a = Range(Selection, Selection.End(xlToRight))
' Loop through each cell in the column
For Each col In a
' Flag to check if value already exists in the table
Dim exists As Boolean
exists = False
' Loop through each field in the recordset
For Each fld In recset.Fields
' Check if the field name matches the cell value
If fld.Name = col.Value Then
exists = True
Exit For
End If
Next
' If the value doesn't exist in the table, prompt user to add it
If exists = False Then
If MsgBox("Add " & col.Value & " to column?", vbYesNo + vbQuestion) = vbYes Then
adocn.Execute "insert into table1 values('" & col.Value & "')"
End If
End If
Next
' Close database connection
adocn.Close
End Sub
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.