阅读 Excel 报告以填充 Access 中的选定信息 table

Reading Excel Report to populate selected information in Access table

我正在尝试从 Excel 报告中导入相关信息,该报告并非专门用于导入数据。基本上它是带有其他信息的格式化报告。请参阅所附图片以获取想法。这是一份庞大的报告,包含数百行。

我正在考虑通过读取 Excel 文件来导入数据,基于特定行的信息,然后将该行插入到 Access table.

我附上了简化版本的报告,让您了解报告布局和访问 table 结构,我想在 table DailyTranaction 中存储的信息。

此处为示例报告图片:

在此处访问 Table 结构图像:

我不确定使用 Access VBA 完成上述任务的最佳方法,非常感谢一个简单的工作示例。

插入new code module然后复制并粘贴以下代码:

Option Compare Database
Option Explicit

Public Function GetDataFromReport(ByVal sRepFileName As String) As Integer
Dim xlApp As Object, xlWbk As Object, xlWsh As Object
Dim retVal As Integer, sRepDate As String, r As Integer, sBranch As String, sQry As String, rs As Integer

On Error GoTo Err_GetDataFromReport

DoCmd.SetWarnings False

Set xlApp = CreateObject("Excel.Application")
Set xlWbk = xlApp.Workbooks.Open(sRepFileName)
Set xlWsh = xlWbk.Worksheets(1) 'or pass the name, ex: "Sheet1"

sRepDate = xlWsh.Range("A1")
r = InStr(1, sRepDate, "th")
sRepDate = Replace(sRepDate, Left(sRepDate, InStr(r - 3, sRepDate, " ")), "")
sRepDate = Replace(sRepDate, "th", "")

'find the last row;
rs = xlWsh.Range("A" & xlWsh.Rows.Count).End(-4162).Row
r = 3
Do While r <= rs
    Select Case UCase(Trim(xlWsh.Range("A" & r)))
        Case "", UCase("CustId")
            'skip empty row and header of data
            GoTo SkipRow

        Case UCase("Branch:")
            sBranch = xlWsh.Range("B" & r)

        Case Else
            'proceed if the value is numeric
            If Not IsNumeric(xlWsh.Range("A" & r)) Then GoTo SkipRow

            sQry = "INSERT INTO Reports([ReportDate],[BranchCode],[CustId],[AccountNo],[Transaction])" & vbCr & _
                    "VALUES(#" & sRepDate & "#," & sBranch & ", " & xlWsh.Range("A" & r) & _
                            ", " & xlWsh.Range("B" & r) & ", " & xlWsh.Range("C" & r) & ")"
            'Debug.Print sQry
            DoCmd.RunSQL sQry
            'get the number of rows affected ;)
            retVal = retVal +1
    End Select

SkipRow:
    r = r + 1
Loop

Exit_GetDataFromReport:
    On Error Resume Next
    DoCmd.SetWarnings True
    Set xlWsh = Nothing
    xlWbk.Close SaveChanges:=False
    Set xlWbk = Nothing
    xlApp.Quit
    Set xlApp = Nothing
    'return value
    GetDataFromReport = retVal
    Exit Function

Err_GetDataFromReport:
    MsgBox Err.Description, vbExclamation, Err.Number
    Resume Exit_GetDataFromReport

End Function

要使用这个,你需要create macro,其中action应该参考上面的函数:

GetDataFromReport ("C:\report.xls") 

如您所见,您需要定义源工作簿的完整路径。

或者,您可以通过创建过程 运行 以上代码:

Sub Test()
    MsgBox GetDataFromReport("D:\Report Daily Transaction.xls") & " records have been imported!", vbInformation, "Message..."
End Sub

或者,您可以创建打开表单的宏。 Sample database and report

祝你好运!