简体   繁体   English

如何正确地从Excel工作表到另一个Excel工作表的VBA连接?

[英]How to properly from VBA connection from Excel sheet to another Excel sheet?

I currently have 2 separate Excel worksheets. 我目前有2个单独的Excel工作表。 One is data entry and another is display. 一个是数据输入,另一个是显示。

The display uses VBA to connect to data entry to obtain data. 显示器使用VBA连接到数据输入以获取数据。 Normally, it functions well enough. 通常,它运行良好。 However I'm required to have the 2 worksheets in separate windows, meaning both can be displayed at the same time in separate windows, in the same screen. 但是,我需要将2个工作表放在单独的窗口中,这意味着两个工作表可以同时在单独的窗口中在同一屏幕中显示。

在此处输入图片说明

The issue in this scenario is that when I click Execute in display to begin SQL query, the display window opens another data entry worksheet (read-only) and reads that instead of the one I opened initially. 在这种情况下的问题是,当我单击“在显示中执行”以开始SQL查询时,显示窗口将打开另一个数据输入工作表(只读),并读取该数据表,而不是我最初打开的表。 Is this issue due to my connection string or my ADODB.Recordset has issues? 是因为我的连接字符串还是我的ADODB.Recordset有问题?

Here is the sub which contains the connection string and ADODB.Recordset. 这是包含连接字符串和ADODB.Recordset的子项。 Edit: Full code is included to provide full context for those who need it. 编辑:包括完整的代码以为需要它的人提供完整的上下文。

Public Sub QueryWorksheet(szSQL As String, rgStart As Range, wbWorkBook As String, AB As String)
Dim rsData As ADODB.Recordset
Dim szConnect As String
On Error GoTo ErrHandler

If AB = "1st" Then
wbWorkBook = ThisWorkbook.Sheets("Inner Workings").Range("B9").Text
End If

Application.StatusBar = "Retrieving data ....."
'Set up the connection string to excel - thisworkbook
szConnect = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
            "Data Source=" & wbWorkBook & ";" & _
            "Extended Properties=Excel 8.0;"

Set rsData = New ADODB.Recordset
'Run the query as adCmdText
rsData.Open szSQL, szConnect, adOpenForwardOnly, adLockReadOnly, adCmdText

'Check if data is returned
If Not rsData.EOF Then
    'if the recordset contains data put them on the worksheet
    rgStart.CopyFromRecordset rsData
Else

End If
'Close connection
rsData.Close
'Clean up and get out
Set rsData = Nothing
Application.StatusBar = False
Exit Sub

ErrHandler:
'an error occured in the SQL-statement
MsgBox "Your query could not be executed, the SQL-statement is incorrect."
Set rsData = Nothing
Application.StatusBar = False

End Sub

Sub process()
Call clear
Call testsql("1st")  ' populate 1st Summary
Call testsql("2nd")  ' find Date+Time
Call testsql("3rd")  ' arrange record by newest
Call testsql("4th")  ' show final results
End Sub

Sub testsql(AB As String)

Dim rgPlaceOutput As Range    'first cell for the output of the query
Dim stSQLstring As String     'text of the cell containing the SQL statement
Dim rg As String, SQL As String

If AB = "1st" Then
stSQLstring = ThisWorkbook.Sheets("Inner Workings").Range("B2").Text
Set rgPlaceOutput = ThisWorkbook.Sheets("1st Summary").Range("A2")
End If
If AB = "2nd" Then
stSQLstring = ThisWorkbook.Sheets("Inner Workings").Range("B3").Text
Set rgPlaceOutput = ThisWorkbook.Sheets("2nd Summary").Range("A2")
End If
If AB = "3rd" Then
stSQLstring = ThisWorkbook.Sheets("Inner Workings").Range("B4").Text
Set rgPlaceOutput = ThisWorkbook.Sheets("3rd Summary").Range("A2")
End If
If AB = "4th" Then
stSQLstring = ThisWorkbook.Sheets("Inner Workings").Range("B5").Text
Set rgPlaceOutput = ThisWorkbook.Sheets("Final Summary").Range("A5")
End If

QueryWorksheet stSQLstring, rgPlaceOutput, ThisWorkbook.FullName, AB

End Sub

Sub clear()
ActiveWorkbook.Sheets("1st Summary").Range("A2:BR5000").Value = Empty
ActiveWorkbook.Sheets("2nd Summary").Range("A2:BR5000").Value = Empty
ActiveWorkbook.Sheets("3rd Summary").Range("A2:BR5000").Value = Empty
ActiveWorkbook.Sheets("Final Summary").Range("A5:BR5000").Value = Empty
End Sub

Also another thing I noticed. 我注意到的另一件事。 Depending on which file I open first, it can result in both files creating a read-only copy when I click Execute. 根据我首先打开的文件,当我单击“执行”时,这可能会导致两个文件都创建一个只读副本。 If I open Display first then Entry form, both in different instances of Excel, it will create read-only copies of both files. 如果我先在不同的Excel实例中打开“显示”,然后打开“条目”窗体,它将创建两个文件的只读副本。

If I open Entry form first, then Display in again, different instances of Excel, only the read-only copy of Display will appear. 如果我先打开“输入”表单,然后再打开“显示” Excel的不同实例,则只会显示“ Display”的只读副本。

The only time a read-only does not appear is when both files are in a single instance of Excel, which is not what I want. 只有两个文件都在单个Excel实例中时才不显示只读,这不是我想要的。

Edit2: EDIT2:

For more info, here is the SQL I used (4 total) 有关更多信息,这是我使用的SQL(共4个)

SQL1 - select * from EntryTable SQL1-从EntryTable选择*

SQL2 - select A.*,[Date + Time] from Summary1 A left join (select [Die No], max (Date + Time) as [Date + Time] from Summary1 group by [Die No]) B on A.[Die No] = B.[Die No] SQL2-从Summary1中选择A。*,[Date + Time]。在A上的左联接(从[Die No]中从Summary1组中选择[Die No],最大(Date + Time)作为[Date + Time])。 Die No] = B. [Die No]

SQL3 - select * from Summary2 where [Date + Time] = Date + Time SQL3-从Summary2中选择*,其中[Date + Time] = Date + Time

SQL4 - select Project_No, Die_No, Description, Repair_Details, Status from Summary3 SQL4-从Summary3中选择Project_No,Die_No,Description,Repair_Details,Status

Workbook name in cell B9 = V:\\Die Maintenance System v2\\Die Maintenance Menu.xlsx 单元格B9中的工作簿名称= V:\\ Die Maintenance System v2 \\ Die Maintenance Menu.xlsx

Update: My colleague has tested the system on her PC and tested no problems. 更新:我的同事已经在她的PC上测试了该系统,并且没有测试任何问题。 I've been told its most likely my Excel settings. 有人告诉我它最有可能是我的Excel设置。 But for the life of me, I can't figure out what is causing it. 但是对于我的一生,我不知道是什么原因造成的。 What type of setting is used to prevent the read-only file from appearing? 哪种类型的设置用于防止出现只读文件?

Edit: I can see that this post has gone on too long. 编辑:我可以看到这篇文章已经进行了太长时间。 I decided to continue this on a new thread right here . 我决定继续这样一个新的线程就在这里

So i would do it with the Workbook.Open() Method. 所以我会用Workbook.Open()方法来做到这一点。

Sub Example()
Dim wb as Workbook
Dim path as String

path = "C:\Users\User\Desktop\1.xlsx"

set wb = Workbook.Open(path) 
End Sub 

Now you can use wb to execute every vba function. 现在,您可以使用wb执行每个vba函数。 Then there a options to check if a workbook is already opened, look here . 然后有一个选项来检查工作簿是否已经打开,请看这里 I dont think you can do that with adodb. 我不认为您可以使用adodb做到这一点。

I tired using ACE and it worked just fine. 我厌倦了使用ACE ,并且效果很好。 It didn't open a new file. 它没有打开新文件。

szConnect = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" & _
            wbWorkBook  & "';" & _
            "Extended Properties='Excel 12.0;HDR=Yes;IMEX=1';"

Your SQL FROM clause is referencing a different named range. 您的SQL FROM子句引用了另一个命名范围。 Please post your SQL text. 请发布您的SQL文本。 It must be qualified to correct Named Range or sheet name. 它必须符合正确的命名范围或工作表名称的条件。

    SELECT Project No, Die No, Description, Repair Details, Status
    FROM DATA1  <- correct this to qualified named range or sheet name

like 喜欢

   FROM [Entry Form$] 'or

   FROM [Named Range] <- this can be found in Formulas | Name Manager

Edit: I am not sure about your "1st" source workbook's location so let us try to insert the line I commented below 编辑:我不确定您的“第一”源工作簿的位置,所以让我们尝试插入我在下面评论的行

   wbWorkBook = ThisWorkbook.Sheets("Inner Workings").Range("B9").Text
   wbWorkBook = Workbooks(wbWorkbook).FullName  '<- add this line

If it still does not work, please post your SQL AND Workbook name in cell B9. 如果仍然不起作用,请在单元格B9中张贴您的SQL AND Workbook名称。

Edit 2: What is the result if you change the FROM clause like: 编辑2:如果像这样更改FROM子句,结果是什么:

   select * from [EntryTable$]

Edit 3: Do you have password? 编辑3:您有密码吗? if so, try to disable it first to isolate the problem in read only. 如果是这样,请尝试先禁用它以将问题隔离为只读。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM