动态添加并运行vba代码

时间:2017-01-04 19:12:28

标签: excel vba excel-vba macros export-to-csv

以下是我目前的步骤

  1. 访问文件按宏(VBA代码)

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

  4. 现在,我在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
    

    note 我不想在某个时间使用Windows调度程序来运行Macro。

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

    我会尽力回应!请留下评论以澄清。谢谢!

1 个答案:

答案 0 :(得分:1)

您只需将现有的第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