如何在excel vba中传递包含excel文件路径的字符串以访问vba
Posted
技术标签:
【中文标题】如何在excel vba中传递包含excel文件路径的字符串以访问vba【英文标题】:How to pass a string contains excel file path in excel vba to access vba 【发布时间】:2014-03-20 17:14:10 【问题描述】:我想传递一个字符串 aPath 包含活动工作簿的路径以访问 vba 模块或子。下面是我的 excel vba 代码,它将打开访问数据库表单。我如何传递字符串值来访问 vba。
Dim aPath, aDbase, aDSource, aTable, exePath As String
Dim fileParam As String
aPath = ActiveWorkbook.Path
aDbase = "near_14.accdb"
aDSource = aPath & "\" & aDbase
Set appAccess = CreateObject("Access.Application")
appAccess.Visible = True
appAccess.OpenCurrentDatabase aDSource
appAccess.DoCmd.OpenForm "Import_From_P"
appAccess.CloseCurrentDatabase
我的 Access VBA 代码将内容写回 excel。我想在其中拥有 aPath conWKB_NAME
中的值 Public Sub sCopyResultstoexcel(conSHT_NAME As Variant, conWKB_NAME As Variant, qrytable As String)
'Copy records to first 20000 rows
'in an existing Excel Workbook and worksheet
Dim objXL As Excel.Application
Dim objWkb As Excel.Workbook
Dim objSht As Excel.Worksheet
Dim db As Database
Dim rs As Recordset
Dim rs_Attribute As Recordset
Dim intLastCol As Integer
Const conMAX_ROWS = 20000
Set db = CurrentDb
Set objXL = New Excel.Application
Set rs = db.OpenRecordset(qrytable, dbOpenSnapshot)
With objXL
.Visible = False
Set objWkb = .Workbooks.Open(conWKB_NAME)
On Error Resume Next
Set objSht = objWkb.Worksheets(conSHT_NAME)
If Not Err.Number = 0 Then
Set objSht = objWkb.Worksheets.Add
objSht.Name = conSHT_NAME
End If
Err.Clear
On Error GoTo 0
intLastCol = objSht.UsedRange.Columns.Count
With objSht
.Range(.Cells(2, 1), .Cells(conMAX_ROWS, _
intLastCol)).CopyFromRecordset rs
.Range(.Cells(1, 1), _
.Cells(1, rs.Fields.Count)).Font.Bold = True
'.Cells.Range(1, rs.Fields.Count).WrapText = True
.Range(.Cells(1, 1), _
.Cells(1, rs.Fields.Count)).WrapText = False
'Formatting
With objSht.Range("A1:AP1")
.HorizontalAlignment = xlCenter
.ColumnWidth = "8"
.Font.Italic = False
.Font.Bold = True
.EntireColumn.ColumnWidth = 15
End With
'Adding fields
With rs
For i = 1 To .Fields.Count
objSht.Cells(1, i) = .Fields(i - 1).Name
Next i
objWkb.Save
End With
End With
End With
objWkb.Close
objXL.Quit
Set objSht = Nothing
Set objWkb = Nothing
Set objXL = Nothing
Set rs = Nothing
Set db = Nothing
End Sub
【问题讨论】:
Access 将如何使用aPath
字符串值?
抱歉,您是在问这个问题吗?是的,我如何使用字符串值进行访问。
我的意思是 Access 在获得该字符串后将如何处理 aPath
。
我更新了问题。请看一下
【参考方案1】:
考虑 Application.Run 方法(有关详细信息,请参阅 Access 帮助主题)。
这样试试吧……
appAccess.OpenCurrentDatabase aDSource
appAccess.Run "sCopyResultstoexcel", "YourSheetName", aPath, _
"your qrytable string"
我认为这就是您的问题所要求的。然而,这一系列操作(从 Excel,打开 Access,然后再次从 Access 打开 Excel)对我来说似乎很复杂。我认为在第一个 Excel 实例中将 Access 数据拉入工作簿中的目标工作表应该更简单。
【讨论】:
是的,它看起来像操作链。简而言之,用户打开 excel 文件,当单击按钮访问表单打开时,用户将在下拉列表中选择一些数据,对应于我将运行查询(方法)来整理表格。我需要将查询结果表写回当前打开的 excel 文件。【参考方案2】:试试这个。将 aPath 调暗为字符串。目前只有 exePath 被声明为字符串。不确定它会起作用,但值得一试。你遇到了什么错误?
【讨论】:
我没有收到错误。我如何传递 aPath 值来访问 vba sub.以上是关于如何在excel vba中传递包含excel文件路径的字符串以访问vba的主要内容,如果未能解决你的问题,请参考以下文章