Этот баннер — требование Роскомнадзора для исполнения 152 ФЗ.
«На сайте осуществляется обработка файлов cookie, необходимых для работы сайта, а также для анализа использования сайта и улучшения предоставляемых сервисов с использованием метрической программы Яндекс.Метрика. Продолжая использовать сайт, вы даёте согласие с использованием данных технологий».
Политика конфиденциальности
|
|
|
запрос из именованной области
|
|||
|---|---|---|---|
|
#18+
Добрый день. Не знает ли кто ответа на такой вопрос. Имеется книга в Excel, данные хранятся на разных листах в именованных областях. Возможно ли сделать выборку из разных областей аналогично SQL запросу и поместить результат в другой лист этой же книги. Можно конечно макросом перебирать записи на листах. Однако много областей и сцеплять их долго. Точно знаю, что из внешней программы можно обращаться к именованным областям Экселевской книги через ODBC и выбирать данные как из таблиц (в Фоксе например). А можно ли в самом Экселе сделать чтото типа : select a.p1, Sum(b.p2) from Лист1, Лист2 where a.p3=b.p3 ... |
|||
|
:
Нравится:
Не нравится:
|
|||
| 06.05.2004, 10:03 |
|
||
|
запрос из именованной области
|
|||
|---|---|---|---|
|
#18+
Спасибо за сответ. Но основной вопрос в том, чтобы select-ом объединить данные из нескольких (многочисленных) именованных диапазонов и поместить результат в другой диапазон. ... |
|||
|
:
Нравится:
Не нравится:
|
|||
| 06.05.2004, 15:08 |
|
||
|
запрос из именованной области
|
|||
|---|---|---|---|
|
#18+
Start Visual Basic and create a new Standard EXE project. Form1 is created by default. Add a CommandButton to Form1. Click References from the Project menu. Add a reference to the Microsoft ActiveX Data Objects 2.1 Library. Paste the following code into the code section of Form1: Private Sub Command1_Click() Dim cnt As New ADODB.Connection Dim rst As New ADODB.Recordset Dim xlApp As Object Dim xlWb As Object Dim xlWs As Object Dim recArray As Variant Dim strDB As String Dim fldCount As Integer Dim recCount As Long Dim iCol As Integer Dim iRow As Integer ' Set the string to the path of your Northwind database strDB = "c:\Program Files\Microsoft Office\Office\Samples\Northwind.mdb" ' Open connection to the database cnt.Open "Provider=Microsoft.Jet.OLEDB.4.0;" & _ "Data Source=" & strDB & ";" ' Open recordset based on Orders table rst.Open "Select * From Orders", cnt ' Create an instance of Excel and add a workbook Set xlApp = CreateObject("Excel.Application") Set xlWb = xlApp.Workbooks.Add Set xlWs = xlWb.Worksheets("Sheet1") ' Display Excel and give user control of Excel's lifetime xlApp.Visible = True xlApp.UserControl = True ' Copy field names to the first row of the worksheet fldCount = rst.Fields.Count For iCol = 1 To fldCount xlWs.Cells(1, iCol).Value = rst.Fields(iCol - 1).Name Next ' Check version of Excel If Val(Mid(xlApp.Version, 1, InStr(1, xlApp.Version, ".") - 1)) > 8 Then 'EXCEL 2000 or 2002: Use CopyFromRecordset ' Copy the recordset to the worksheet, starting in cell A2 xlWs.Cells(2, 1).CopyFromRecordset rst 'Note: CopyFromRecordset will fail if the recordset 'contains an OLE object field or array data such 'as hierarchical recordsets Else 'EXCEL 97 or earlier: Use GetRows then copy array to Excel ' Copy recordset to an array recArray = rst.GetRows 'Note: GetRows returns a 0-based array where the first 'dimension contains fields and the second dimension 'contains records. We will transpose this array so that 'the first dimension contains records, allowing the 'data to appears properly when copied to Excel ' Determine number of records recCount = UBound(recArray, 2) + 1 '+ 1 since 0-based array ' Check the array for contents that are not valid when ' copying the array to an Excel worksheet For iCol = 0 To fldCount - 1 For iRow = 0 To recCount - 1 ' Take care of Date fields If IsDate(recArray(iCol, iRow)) Then recArray(iCol, iRow) = Format(recArray(iCol, iRow)) ' Take care of OLE object fields or array fields ElseIf IsArray(recArray(iCol, iRow)) Then recArray(iCol, iRow) = "Array Field" End If Next iRow 'next record Next iCol 'next field ' Transpose and Copy the array to the worksheet, ' starting in cell A2 xlWs.Cells(2, 1).Resize(recCount, fldCount).Value = _ TransposeDim(recArray) End If ' Auto-fit the column widths and row heights xlApp.Selection.CurrentRegion.Columns.AutoFit xlApp.Selection.CurrentRegion.Rows.AutoFit ' Close ADO objects rst.Close cnt.Close Set rst = Nothing Set cnt = Nothing ' Release Excel references Set xlWs = Nothing Set xlWb = Nothing Set xlApp = NothingEnd Sub Function TransposeDim(v As Variant) As Variant ' Custom Function to Transpose a 0-based array (v) Dim X As Long, Y As Long, Xupper As Long, Yupper As Long Dim tempArray As Variant Xupper = UBound(v, 2) Yupper = UBound(v, 1) ReDim tempArray(Xupper, Yupper) For X = 0 To Xupper For Y = 0 To Yupper tempArray(X, Y) = v(Y, X) Next Y Next X TransposeDim = tempArrayEnd Function Press the F5 key to run the project. Form1 appears. Click the CommandButton on Form1, and note that the contents of the Orders table is displayed in a new workbook in Excel. ... |
|||
|
:
Нравится:
Не нравится:
|
|||
| 07.05.2004, 12:09 |
|
||
|
запрос из именованной области
|
|||
|---|---|---|---|
|
#18+
Используй ODBC как в фоксе. Внутрях екселя сделай ссылку на ADO, напиши макрос, выплняющий запрос типа Insert into <именованная область> select * from <именованная область>; выбранные же рекордсеты только для чтения, какие курсоры не используй. Не знаю только, сработает ли это из того же файла. ... |
|||
|
:
Нравится:
Не нравится:
|
|||
| 07.05.2004, 12:57 |
|
||
|
запрос из именованной области
|
|||
|---|---|---|---|
|
#18+
Antonariyвыбранные же рекордсеты только для чтения, какие курсоры не используй. Не знаю только, сработает ли это из того же файла. Из того же файла работает пучком и курсор дозволяет редактирование: Код: plaintext 1. 2. 3. 4. 5. 6. ... |
|||
|
:
Нравится:
Не нравится:
|
|||
| 07.05.2004, 16:01 |
|
||
|
запрос из именованной области
|
|||
|---|---|---|---|
|
#18+
спасибо за помощь, заработало через ADODB.Connection Set oconnection = CreateObject("ADODB.Connection") oconnection.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Trim(ActiveWorkbook.FullName) + ";Extended Properties=""Excel 8.0;HDR=NO""" sqltext = "SELECT ....." Set oRS = oconnection.Execute(sqltext) With ActiveWorkbook.Worksheets("Rezult").QueryTables.Add(oRS, Destination:=Worksheets("Rezult").Range("A1")) .Name = "Rezult1" .FieldNames = True .RowNumbers = False .FillAdjacentFormulas = False .PreserveFormatting = True .RefreshOnFileOpen = False .BackgroundQuery = True .RefreshStyle = xlInsertDeleteCells .SaveData = True .AdjustColumnWidth = True .RefreshPeriod = 0 .PreserveColumnInfo = True .Refresh BackgroundQuery:=False End With Результат помещается в лист Rezult1 в именованный диапазон Rezult, а вот если запрос уже из него сделать то не выходит, пищет что объект Result1 не найден. причем в списке именованных областей его видно. ... |
|||
|
:
Нравится:
Не нравится:
|
|||
| 11.05.2004, 14:55 |
|
||
|
запрос из именованной области
|
|||
|---|---|---|---|
|
#18+
авторРезультат помещается в лист Rezult1 в именованный диапазон Rezult, а вот если запрос уже из него сделать то не выходит, пищет что объект Result1 не найден. причем в списке именованных областей его видно. Всё правильно, файл-то не сохранён... ... |
|||
|
:
Нравится:
Не нравится:
|
|||
| 11.05.2004, 18:12 |
|
||
|
|

start [/forum/topic.php?fid=60&fpage=374&tid=2169600]: |
0ms |
get settings: |
7ms |
get forum list: |
17ms |
check forum access: |
3ms |
check topic access: |
3ms |
track hit: |
31ms |
get topic data: |
10ms |
get forum data: |
2ms |
get page messages: |
51ms |
get tp. blocked users: |
1ms |
| others: | 229ms |
| total: | 354ms |

| 0 / 0 |
