1

この質問の後:別のワークブックを開かずに値/チャートを取得する

私はこれをコーディングしました:

Sub test()

Dim oConn As New ADODB.Connection
Dim rst As New ADODB.Recordset

oConn.Provider = "Microsoft.Jet.OLEDB.4.0"
oConn.Properties("Extended Properties").Value = "Excel 8.0"
oConn.Open "C:\Workbook1.xlsm"
rst.Open "SELECT * FROM [A1:A2];", oConn, adOpenStatic

rst.MoveFirst
MsgBox rst.Fields(0)

rst.Close
oConn.Close

End Sub

今のところ、私の目標はcell A1of のの値を取得することsheet 1ですworkbook1.xlsm

私は2つの問題に遭遇しました。

workbook1開いていないときは

Run time error '-214767259 (80004005)': Automation error Unspecified Error on the line      oConn.Open "C:\Workbook1.xlsm`   

ワークブックを開かずに作業したいので、これは面倒です。ワークブックが開いているときにうまく機能します。

2 番目の問題: 単一のセル値しか取得できません。のみ入力しようとしまし[A1]rst.openが、うまくいきません。アドレスで一意のセル値を取得するにはどうすればよいですか? その名前で?

4

2 に答える 2

3

よろしければ、データを取得するための少し異なる試みを提供します。違いは、データベース (Excel シート) に接続する方法です。ただし、いくつかの重要な要素をコードに組み込むことができます。そのため、以下のコード内のコメントを確認してください。

Sub Closed_excel_workbook()

    Dim myConnection As String
    Dim myRecordset As ADODB.Recordset
    Dim mySQL As String

'connection string parameters
'CHANGE PATH TO YOUR CLOSED WORKBOOK
    myConnection = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
               "Data Source=" & ThisWorkbook.Path & "\Dane\BazaDanych.xlsx;" & _
               "Extended Properties=Excel 12.0"

'here is important, YOU CAN'T MISS SHEET NAME
    mySQL = "SELECT * FROM [ARKUSZ1$a1:a2]"

'different way of getting data from excel sheet
    Set myRecordset = New ADODB.Recordset
    myRecordset.Open mySQL, myConnection, adOpenUnspecified, adLockUnspecified

'let's clear sheet before pasting data
'REMOVE IF NOT NEEDED
    ActiveSheet.Cells.Clear

'HERE WE PASTING DATA WE HAVE RETRIEVED
    ActiveSheet.Range("A2").CopyFromRecordset myRecordset

'OPTIONAL, IF REQUIRED YOU CAN ADD COLUMNS NAMES
    Dim cell As Range, i!
    With ActiveSheet.Range("A1").CurrentRegion
        For i = 0 To myRecordset.Fields.Count - 1
            .Cells(1, i + 1).Value = myRecordset.Fields(i).Name
        Next i
        .EntireColumn.AutoFit
    End With
End Sub
于 2013-05-31T18:34:12.793 に答える
1

私の解決策:

Function GetValue()

Path = "C:\Path\"
    File = "Doc.xlsm"
    Sheet = "Sheet_name"
    Ref = "D4"

     'Retrieves a value from a closed workbook
    Dim Arg As String
     'Make sure the file exists
   If Right(Path, 1) <> "\" Then Path = Path & "\"
   If Dir(Path & File) = "" Then
       GetValue = "File not  Found"
       Exit Function
    End If
     'Create the argument
    Arg = "'" & Path & "[" & File & "]" & CStr(Sheet) & "'!" & Range(Ref).Range("A1").Address(, , xlR1C1)
     'Check the value

     MsgBox Arg

    'Execute XML

    GetValue = ExecuteExcel4Macro(Arg)
End Function

複雑な adodb 接続を使用しないという利点がありますが、それほど強力ではない可能性があります。

于 2013-06-04T15:12:00.407 に答える