VBA运行时出现类型不匹配错误,请求协助定位问题
Let’s break down the likely causes of the "Type mismatch" error in your code and walk through fixes for each:
1. Mismatched Recordset Type Assignment
The line Set rs = Grid.DataSource is the most probable culprit here. You’ve declared rs as an ADODB.Recordset, but Grid.DataSource might be returning a different recordset type (like a DAO.Recordset) or even a non-recordset object depending on your grid control’s behavior.
Fix:
- First, confirm what type of object
Grid.DataSourcereturns. If it’s a DAO.Recordset, update your declaration to:Dim rs As DAO.Recordset - If your grid control supports it, use its built-in methods to retrieve an
ADODB.Recordsetexplicitly instead of relying directly onDataSource.
2. Out-of-Order Connection Setup
You’re attempting to call rs.AddNew before configuring the Adodc1 connection string. Even if rs was properly assigned, the underlying connection isn’t initialized yet, which can lead to unexpected type errors when interacting with the recordset.
Fix:
- Rearrange your code to set up the connection before modifying the recordset, and ensure you’re using the correct connection object (you created
GSBMconnbut haven’t linked it toAdodc1):Adodc1.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\YourDatabasePath.mdb;" ' Complete your connection string Adodc1.Refresh ' Apply the connection settings Set rs = Grid.DataSource ' Assign the recordset only after the connection is ready
3. Undeclared/Ambiguous Connection Variable
GSBMconn isn’t declared inside your subroutine, meaning it’s relying on a global declaration. If that global variable isn’t explicitly typed as ADODB.Connection, this could introduce type mismatch issues.
Fix:
- Add an explicit declaration inside the sub to avoid scope confusion:
Dim GSBMconn As ADODB.Connection Set GSBMconn = New ADODB.Connection - If you intend to use
GSBMconnwithAdodc1, link them withAdodc1.Connection = GSBMconnafter opening the connection.
4. Incomplete AddNew Implementation
Your provided code cuts off after setting the connection string, so make sure you complete the AddNew workflow properly. Forgetting to assign field values or call rs.Update can lead to follow-up errors, even if the initial type mismatch is fixed.
内容的提问来源于stack exchange,提问作者wasif khan

