2016-11-01 95 views
0

我正在使用Access VBA連接到SQL Server,並從指定的數據庫中打印出表信息。我可以連接,並且我可以打印出表格信息沒有問題。當我添加一條IF聲明時,我的代碼就會一直執行,並且從不打印出所需的結果。例如,我的Debug.Print語句將返回僅從特定表中打印數據

Test_1 
Test_2 
Red 
Blue 

但是,如果我去掉if語句,並試圖執行語法,不會引發錯誤和訪問只是凍結了我的電話。我希望得到的結果是打印兩個表名稱Like Test*我的語法應如何更改才能打印此數據?

Public Sub GetTableNames() 
Dim c As ADODB.Connection 
Dim r As ADODB.Recordset 
Dim f As ADODB.Field 
Set c = New ADODB.Connection 
With c 
.Provider = "sqloledb.1" 
With .Properties 
    .Item("Data Source") = "server" 
    .Item("Initial Catalog") = "database" 
    .Item("PassWord") = "password" 
    .Item("User ID") = "userid" 
End With 
.Open 
Set r = .OpenSchema(adSchemaTables,Array(Empty, Empty, Empty, "TABLE")) 
With r 
    While Not .EOF 
     'IF (.Fields("Table_Name") LIKE "Test*") THEN 
      Debug.Print .Fields("TABLE_NAME"), .Fields("TABLE_TYPE") 
      .MoveNext 
     'END IF 
    Wend 
End With 
End With 
End Sub 

回答

0

你就近了。您的問題不在於IF聲明,它與.MoveNext的定位有關。由於該聲明位於IF塊內,因此您永遠不會迭代到下一個表,因此每次只查看第一個表。據說,我認爲Blue是你的第一個表名。

將您的代碼更改爲此,您將全部設置。

Public Sub GetTableNames() 
Dim c As ADODB.Connection 
Dim r As ADODB.Recordset 
Dim f As ADODB.Field 
Set c = New ADODB.Connection 
With c 
.Provider = "sqloledb.1" 
With .Properties 
.Item("Data Source") = "server" 
.Item("Initial Catalog") = "database" 
.Item("PassWord") = "password" 
.Item("User ID") = "userid" 
End With 
.Open 
Set r = .OpenSchema(adSchemaTables,Array(Empty, Empty, Empty, "TABLE")) 
With r 
While Not .EOF 
    IF (.Fields("Table_Name") LIKE "Test*") THEN 
     Debug.Print .Fields("TABLE_NAME"), .Fields("TABLE_TYPE")    
    END IF 
    .MoveNext 
Wend 
End With 
End With 
End Sub