2017-01-04 83 views
2

以下是我目前的步驟動態添加和運行VBA代碼

  1. 訪問文件導出CSV文件的宏(VBA代碼)

  2. 導出CSV文件通過宏來得到修改(VBA代碼)

現在,我在執行上接入宏(步驟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

我會盡我所能來響應!請留下澄清意見。謝謝!

+0

(a)你不能有VBA的CSV文件 - 一個CSV文件是一個簡單的文本文件。 (b)不用通過宏刪除行,爲什麼你不打擾寫這些記錄到原始的CSV文件? (c)我只注意到你的文件不是CSV文件,它是一個帶有CSV擴展名的管道分隔文件。 – YowE3K

+0

@ YowE3K感謝您的評論!由於它是一個與Access連接的SQL服務器,因此我不可能編輯它。 –

+0

所以你不能編輯「第1步」的代碼?它不是Access VBA? – YowE3K

回答

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 
+0

所以你已經編輯到CDate(rst(3))> = Date!我看到你在那裏做什麼!謝謝你會告訴你它是如何工作的! –

+0

非常感謝!你是個天才! :)你找到了一個更簡單的方法來解決它!再次感謝您 –

+0

只需檢查下游進程是否需要逗號或管道作爲分隔符。我的猜測是,您的舊方法是將文件從excel中保存爲真正的逗號分隔值文件,而Access則將其保存爲管道分隔符。 (您可能需要在我發佈的代碼中將'「|」'更改爲'「,」'。) – YowE3K