周期性地,相同或相似的问题出现在我们的Access论坛中:如何在Access中使用Excel函数? 因此,我决定制作本周主题TheScripts Tip。 为了演示在Access上下文中Excel函数的使用,我依次执行了以下步骤:
- 创建了一个名为fStripNonPrintableCharacters()的公共函数,它将封装用于执行Excel函数的逻辑。 此访问函数将接受一个单独的参数(STRING),Excel函数将在该参数上运行。 所选的Excel函数将很快介绍。
- 创建一个Excel实例,并将其分配给一个对象变量。
- 通过将单个参数传递给访问函数的对象变量来执行Excel函数。 此参数将由预定义的字符串值组成。
- 将Excel函数的返回值设置为Access函数的返回值。
- 销毁对象变量引用的Excel实例,然后将变量设置为Nothing,以释放分配给它的所有资源。
概述已经足够了! 现在,我将显示相关代码和后续输出。 该代码已被很好地记录下来,但是如果您需要对本技巧的任何方面进行说明,请随时提出。
- 执行脏工作的实际功能:
Public Function fStripNonPrintableCharacters(strStringToStrip As String) As String 'Make sure to 1st set a Reference to the Microsoft Excel XX.X Object Library Dim objExcel As Excel.Application Set objExcel = CreateObject("Excel.Application") fStripNonPrintableCharacters = objExcel.Application.Clean(strStringToStrip) End Function
- 函数调用和证明其成功的逻辑:
Dim strStringWithNonPrintables As String, strCleanedString As String Dim intCharCounter As Integer, strTempUnclean As String, strTempClean As String, strProveClean As String 'Create a String with 5 Non-Printable Characters contained in it strStringWithNonPrintables = Chr(7) & "ne" & Chr(13) & "a" & Chr$(10) & "to" & Chr(9) & "!" & Chr(5) 'Code Segment not required, used only to demonstrate the presence of Non-Printable characters in String strTempUnclean = "|" For intCharCounter = 1 To Len(strStringWithNonPrintables) 'Build a String containing the ASCII Codes for all characters within the String as well as the character itself delimited by a '|'. Remember Non-Printable Characters have ASCII Codes between 0 and 31 and in this case will be in positions 1, 4, 6, 9, and 11. strTempUnclean = strTempUnclean & Asc(Mid$(strStringWithNonPrintables, intCharCounter, 1)) & _ "-" & Mid$(strStringWithNonPrintables, intCharCounter, 1) & "|" Next 'Dump this String to the Immediate Window to see the Non-Printable Characters represented by ASCII Codes 7, 13, 10, 9, and 5. The Characters will also be represented. We'll ompare this afterwards, when this String is run through Excel's Clean() Function Debug.Print strTempUnclean 'Run the String with Non-Printable Characters through the Clean() Function, print out the result, then prove it worked by using the same logic that was used on the original String. strTempClean = fStripNonPrintableCharacters(strStringWithNonPrintables) Debug.Print strTempClean '==> Prints neato! 'Code Segment not required, used only to verify that Non-Printable characters were removed from String strProveClean = "|" For intCharCounter = 1 To Len strTempClean) strProveClean = strProveClean & Asc(Mid$(strTempClean, intCharCounter, 1)) & _ "-" & Mid$(strTempClean, intCharCounter, 1) & "|" Next Debug.Print strProveClean
- 通过Clean()函数运行之前的字符串(ASCII代码和字符):
|7-|110-n|101-e|13- from Line #19 |97-a|10- |116-t|111-o|9- |33-!|5-|
- 通过Clean()函数运行后的字符串输出(字符/ ASCII代码/字符)
neato! from Line #24 |110-n|101-e|97-a|116-t|111-o|33-!| from Line #33
From: https://bytes.com/topic/access/insights/726129-how-use-excel-functions-access