Excel VBA宏图形动态

时间:2013-10-28 22:20:00

标签: excel vba excel-vba excel-2007

我有一个excel文件会自动打开然后运行一个宏。此宏从txt文件导入数据。每隔1小时,数据就会进入一个新行(时间戳和一个值)的txt文件。我的宏在下午5点打开,导入数据,绘制图表,将其保存到动态日期,然后关闭。

这个宏每天下午5点开放一次。但是,我不希望宏继续选择第一天的前24行和第二天的第二行24行。 当它在第二天运行时。在第二天,我想只选择行(25-49)。在第三天,我想选择行(50-74)。

有没有人有关于使用同一个宏动态选择行的方法?

Sub Auto_Open()
'
' Auto_Open Macro
'

'
    Workbooks.OpenText Filename:="C:\Users\Pablo\Desktop\LOGTEST.txt", Origin _
        :=437, StartRow:=1, DataType:=xlDelimited, TextQualifier:=xlDoubleQuote _
        , ConsecutiveDelimiter:=False, Tab:=False, Semicolon:=True, Comma:= _
        False, Space:=False, Other:=False, FieldInfo:=Array(Array(1, 4), Array(2, 1) _
        ), TrailingMinusNumbers:=True
    Columns("A:A").EntireColumn.AutoFit
    Columns("A:B").Select
    ActiveSheet.Shapes.AddChart.Select
    ActiveChart.SetSourceData Source:=Range("'LOGTEST'!$A:$B")
    ActiveChart.ChartType = xlXYScatterSmoothNoMarkers
    myFileName = "myFile_" & Month(Now) & "_" & Day(Now) & "_" & Hour(Now) & "_" & Minute(Now)
    ActiveWorkbook.SaveAs Filename:="C:\Users\Pablo\Desktop\" & myFileName, _
        FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False

    ActiveWorkbook.Close savechanges = True
    Application.Quit
End Sub

2 个答案:

答案 0 :(得分:0)

在内存中读取文件,而不是将其放入电子表格中:

dFirstDate = #10/1/2013#
dDate = Now
nDays = DateDiff("d", dDate, dFirstDate)
nRowStart = nDays * 24
sFile = "C:\Users\Pablo\Desktop\LOGTEST.txt"
Open sFile For Input As iFileNum
Line Input #iFileNum, sBuf
While Not sBuf = "" And Len(sBuf) > 1
    nFileRow = nFileRow + 1
    If nFileRow >= nRowStart And nFileRow <= nRowStart + 24 Then
        ActiveSheet.Range("A1").Offset(nSheetRow, 0).Value = sBuf
        nSheetRow = sSheetRow + 1
    End If
    Line Input #iFileNum, sBuf
Wend
Close #iFileNum

答案 1 :(得分:0)

Sub Auto_Open()
Const F_PATH As String = "C:\_stuff\"
Dim wb As Workbook, sht As Worksheet, rng As Range
Dim cht As Chart, myFileName As String

    Workbooks.OpenText Filename:=F_PATH & "test.txt", Origin:=437, _
        StartRow:=1, DataType:=xlDelimited, TextQualifier:=xlDoubleQuote, _
        ConsecutiveDelimiter:=False, Tab:=True, Semicolon:=False, _
        Comma:= False, Space:=False, Other:=False, _
        FieldInfo:=Array(Array(1, 4), Array(2, 1)), TrailingMinusNumbers:=True

    Set wb = ActiveWorkbook
    Set sht = wb.Sheets(1)
    Set rng = sht.Cells(Rows.Count, 1).End(xlUp)

    'just use the last 24 rows...
    If rng.Row >= 24 Then Set rng = rng.Offset(-23, 0)
    Set rng = rng.Resize(24, 2)

    sht.Columns(1).EntireColumn.AutoFit

    Set cht = ActiveSheet.Shapes.AddChart(Top:=100, Left:=100).Chart
    cht.SetSourceData Source:=rng
    cht.ChartType = xlXYScatterSmoothNoMarkers

    myFileName = "myFile_" & Month(Now) & "_" & Day(Now) & _
                   "_" & Hour(Now) & "_" & Minute(Now)
    wb.SaveAs Filename:=F_PATH & myFileName, _
        FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False

    wb.Close savechanges:=True
    Application.Quit
End Sub