gpt4 book ai didi

vba - 动态添加并运行一段vba代码

转载 作者:行者123 更新时间:2023-12-02 03:08:03 24 4
gpt4 key购买 nike

以下是我目前的步骤

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

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

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

我想简化这个过程。

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

第一步代码

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

第二步代码

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 scheduler 来运行 Macro。

到目前为止我的好引用是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

关于vba - 动态添加并运行一段vba代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41471556/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com