动态添加 运行 一个 vba 代码

Dynamically add and run a vba code

以下是我目前的步骤

  1. Access文件通过宏(VBA代码)导出CSV文件

  2. 导出的 CSV 文件被宏修改(VBA 代码)

现在,我正在 Access 上执行宏(第 1 步)-> 在导出的文件下,添加代码和 运行(第 2 步)

我想简化流程。

是否可以通过执行第 1 步,将第 2 步代码添加到 csv 文件并运行?

第 1 步代码

Dim dbs As DAO.Database
Dim rst As DAO.Recordset
Dim intFile As Integer
Dim strFilePath As String
Dim intCount As Integer
Dim strHold    
strFilePath = "C:\temp\TEST.csv"    
Set dbs = CurrentDb    
Set rst = dbs.OpenRecordset("Import", dbOpenForwardOnly)    
intFile = FreeFile
Open strFilePath For Output As #intFile    
Do Until rst.EOF
   For intCount = 0 To rst.Fields.Count - 1
   strHold = strHold & rst(intCount).Value & "|"
   Next
   If Right(strHold, 1) = "|" Then
      strHold = Left(strHold, Len(strHold) - 1)
   End If
   Print #intFile, strHold
   rst.MoveNext
   strHold = vbNullString
Loop    
Close intFile    
rst.Close    
Set rst = Nothing        
End Function

第 2 步代码

Sub deleterows()
lastrow = Cells(Rows.Count, 4).End(xlUp).Row
For i = lastrow To 1 Step -1
    If Cells(i, 4).Value < Date Then Rows(i).EntireRow.Delete
Next i
End Sub

注意 我不喜欢在特定时间使用 windows 调度程序到 运行 宏。

到目前为止我的好参考是Is it possible to automatically input VBA code when a new sheet is generated? & Dynamically insert macro into a new excel workbook & https://support.microsoft.com/en-us/kb/219905

我会尽力回复!请发表评论以进行澄清。谢谢!

您只需将现有的第 1 步代码更改为:

Dim dbs As DAO.Database
Dim rst As DAO.Recordset
Dim intFile As Integer
Dim strFilePath As String
Dim intCount As Integer
Dim strHold    
strFilePath = "C:\temp\TEST.csv"    
Set dbs = CurrentDb    
Set rst = dbs.OpenRecordset("Import", dbOpenForwardOnly)    
intFile = FreeFile
Open strFilePath For Output As #intFile    
Do Until rst.EOF
   'Check the 4th field to see whether it is today or later
   If CDate(rst(3)) >= Date Then
       'If so, create a record (if not, don't)
       For intCount = 0 To rst.Fields.Count - 1
           strHold = strHold & rst(intCount).Value & "|"
       Next
       If Right(strHold, 1) = "|" Then
           strHold = Left(strHold, Len(strHold) - 1)
       End If
       Print #intFile, strHold
   End If
   rst.MoveNext
   strHold = vbNullString
Loop    
Close intFile    
rst.Close    
Set rst = Nothing        
End Function