vba让用户从ms访问中选择工作表上的范围

时间:2017-02-10 18:08:03

标签: excel vba excel-vba ms-access-2010

下面的子RangeSelectionPrompt让用户选择一系列单元格。 以下代码仅在此代码位于Excel文件上时才有效。

我想知道在MSAccess中执行此代码。我想捕获用户选择的范围并进行数据操作。 它是可能的还是我抽烟了。

从Access我知道如何午餐Excel,检测打开的WBK数量,在工作簿中导航,.... 表单Excel我知道如何创建一个加载项,连接到数据库并在用户选择后传输数据,但这不是我想要的。

Sub RangeSelectionPrompt()
    Dim rng As Range
    Set rng = Application.InputBox("Select a range", "Obtain Range Object", Type:=8)

    MsgBox "The cells selected were " & rng.Address
End Sub

1 个答案:

答案 0 :(得分:2)

问题已解决

Option Compare Database

Option Explicit
Dim xlApp As Excel.Application
Dim xlWB As Excel.Workbook
Dim rng As Range


Sub GetUserSelection()
    On Error GoTo ErrExcelinstance

    Set xlApp = GetObject(, "Excel.Application")
    Set xlWB = xlApp.ActiveWorkbook              ' the bug was Set xlWB = xlApp.ActiveWorkbook.ActiveSheet.Select

    RangeSelectionPrompt

    Exit Sub

ErrExcelinstance:


    Select Case Err.Number

    Case 429

        Err.Clear
        MsgBox "No Workbook Open"
        Set xlApp = Nothing
        Set xlWB = Nothing


    Case Else

        Set xlApp = Nothing
        Set xlWB = Nothing
        MsgBox Err.Number & "  " & Err.Description
        Err.Clear

    End Select

End Sub


Sub RangeSelectionPrompt()
    On Error GoTo RangeSelectionPrompterr:

    Set rng = xlApp.InputBox("Select a range", "Obtain Range Object", Type:=8)

    MsgBox "The cells selected were " & rng.Address

    Exit Sub

RangeSelectionPrompterr:


    Select Case Err.Number



    Case 424

        Err.Clear
        MsgBox "User did not perform selection"
        Set xlApp = Nothing
        Set xlWB = Nothing


    Case Else



        Set rng = Nothing
        MsgBox Err.Number & "  " & Err.Description
        Err.Clear

    End Select


End Sub