大家好,我是MS Access的新手,确实很难使用VBA联接表。本质上,我需要一个按钮,该按钮将在单击时连接表。虽然这个主题已经完成,但我似乎无法理解它是如何工作的。
问题:假设我有三个表:Tab1,Tab2和Tab3。我想通过一个公共变量加入Tab1和Tab2:通过一个公共变量ID2加入ID和Tab2和Tab3。如何在VBA中编写此代码以返回包含Tab1,Tab2和Tab3的数据表。
即
Tab1
ID Name Age
1 John 22
2 Conor 21
3 Sarah 23
Tab2
ID Name Location
1 John California
2 Conor New York
3 Sarah Washington
Tab3
ID2 Grade
1 A
2 E
3 C
应导致:
Result
ID Name Age Location Grade
1 John 22 California A
2 Conor 21 New York E
3 Sarah 23 Washington C
答案 0 :(得分:0)
SELECT *
FROM (Tab1
inner JOIN Tab2 ON tab1.Id = Tab2.ID)
inner JOIN Tab3 ON tab2.id2 = tab3.id2
丑陋的我知道。
此SQL基于您编辑的问题以及示例数据:
SELECT tab1.*, tab2.Location, tab3.Grade
FROM (Tab1
inner JOIN Tab2 ON tab1.Id = Tab2.ID)
inner JOIN Tab3 ON tab2.id2 = tab3.id2
答案 1 :(得分:-1)
最简单的方法可能是在SQL中执行,然后将SQL转换为VBA。
创建表单
该表单仅需要两个文本框和一个命令按钮。 SQL语句可能很长,因此您将文本框放在选项卡控件的不同页面上。
Create a new form (in design view.)
Add a tab control.
In the first page of the tab control, add a unbound text box.
Set its Name property to txtSql.
Increase its Height and Width so you can see many long lines at once.
In the second page of the tab control, add another unbound text box.
Name it txtVBA, and increase its height and width.
Above the tab control, add a command button.
Name it cmdSql2Vba.
Set its On Click property to [Event Procedure].
Click the Build button (...) beside this property.
When Access opens the code window, set up the code like this:
Private Sub cmdSql2Vba_Click()
Dim strSql As String
'Purpose: Convert a SQL statement into a string to paste into VBA code.
Const strcLineEnd = " "" & vbCrLf & _" & vbCrLf & """"
If IsNull(Me.txtSQL) Then
Beep
Else
strSql = Me.txtSQL
strSql = Replace(strSql, """", """""") 'Double up any quotes.
strSql = Replace(strSql, vbCrLf, strcLineEnd)
strSql = "strSql = """ & strSql & """"
Me.txtVBA = strSql
Me.txtVBA.SetFocus
RunCommand acCmdCopy
End If
End Sub
使用表格
使用表格:
Open your query in SQL View, and copy the SQL statement to clipboard (Ctrl+C.)
Paste into the first text box (Ctrl+V.)
Click the button.
Paste into a new line in your VBA procedure (Ctrl+V.)