如何在Excel中重复固定行数的宏代码?

时间:2012-10-09 22:51:27

标签: excel-vba excel-2010 vba excel

我对宏和VB都很陌生,所以对任何帮助都会感激不尽。 我有以这种形式的数据:

Clip    PSNR-codec1     PSNR-codec2     Bit Rates 
Video1  29.426086       29.220891       94357
Video1  31.207342       31.703124       322832
Video1  34.474587       34.255598       633468
Video1  36.445279       35.479189       936961
Video1  39.093937       36.4768         1539093
Video2  41.156012       37.295318       326742
Video2  43.355358       37.684239       604494
Video2  29.95337        29.30644        1218206
Video2  32.040252       30.837518       1809751
Video2  34.194409       32.774954       2387549
Video3  35.495356       33.806537       1567065
Video3  36.395173       34.544676       2173151
Video3  37.077718       35.234943       3094348
Video3  35.681498       36.036972       3240981
Video3  171.661771      83.104314       3355959
Video4  171.247791      96.978608       5103370
Video4  185.239286      128.064048      6636778
Video4  189.115735      115.418461      8150015
Video4  185.35225       154.3189011     2345629

我的要求是在每个视频的单独表格中创建一个“XYScatterSmooth”类型的图表。该图应在X轴上具有比特率,在Y轴上具有PSNR。展望未来,我们还将提供更多视频的数据。那么如何编写一个宏,它将为每个视频重复这些步骤(即循环应该每5行重复一次.5行数据是固定数字)

Excel版本:2010

1 个答案:

答案 0 :(得分:0)

这对我提供了您提供的样本数据。

将所有数据放在第一张纸上,删除任何其他纸张。您的数据需要从第2行开始(如上所述)。宏将询问您视频的总数(我发现这比循环一个空单元格更容易),然后在新工作表上创建图表。它将工作表命名为Video1,Video2等。

让我知道它是否适合你。

Private Sub BitRateCharts()

' Data should be on Sheet 1. Delete all other sheets.


    Dim nVideoNum As Integer
    nVideoNum = 1

    Dim n As Integer
    n = 1

    Dim nStart As Integer
    nStart = 2

    Dim nLast As Integer
    nLast = 6

    Dim nVideos As Integer
    nVideos = InputBox("How many videos?")

    Dim nSheetNum
    nSheetNum = ActiveSheet.Index

    Do Until n > nVideos

    nSheetNum = ActiveSheet.Index
        If nSheetNum = ThisWorkbook.Sheets.Count Then
            Worksheets.Add(After:=Worksheets(Worksheets.Count)).Name = "Video" & nVideoNum
        Else
        End If

            ActiveSheet.Shapes.AddChart.Select
            ActiveChart.ChartType = xlXYScatterSmoothNoMarkers
            ActiveChart.SetSourceData Source:=Range("Sheet1!$B$" & nStart & ":$D$" & nLast & "")
            ActiveChart.SeriesCollection(1).XValues = "=Sheet1!$D$" & nStart & ":$D$" & nLast & ""
            ActiveChart.SeriesCollection(1).Values = "=Sheet1!$B$" & nStart & ":$B$" & nLast & ""
            ActiveChart.SeriesCollection(2).XValues = "=Sheet1!$D$" & nStart & ":$D$" & nLast & ""
            ActiveChart.SeriesCollection(2).Values = "=Sheet1!$C$" & nStart & ":$C$" & nLast & ""
            ActiveChart.SeriesCollection(1).Name = "=""PSNR-Codec1"""
            ActiveChart.SeriesCollection(2).Name = "=""PSNR-codec2"""

            n = n + 1

            nVideoNum = nVideoNum + 1

            nStart = nStart + 5
            nLast = nLast + 5
    Loop

    MsgBox ("Macro Complete.")

Exit Sub

ErrMsg:

    MsgBox ("Error encountered. Macro could not complete.")


End Sub