用于添加具有特定标头的列并在所有行中填充默认值的宏

时间:2016-07-21 05:57:11

标签: excel vba macros

我需要在数据的最后一个标题单元格旁边添加一个新列,并用一些随机值填充新列,说“酷!”在给定的工作表中。

以下是我的宏:

Func<Task> action = async () =>
{
    Console.WriteLine("Action start...");
    await Task.Delay(1000);
    throw new Exception("Exception from an async action");
};

try
{
   await Task.Run(action);
}
catch(Exception ex)
{
    Console.WriteLine(ex.Message);
}

Console.ReadKey(); 

添加值:

Sub sbInsertingColumns(sourceFile As String, Worksheet As String)
Dim lastColName As String
Dim LastColumn As Long
    With ActiveSheet
        LastColumn = Workbooks(sourceFile).Worksheets(Worksheet).Range("A1").End(xlToRight).Column
    End With
    Dim nextCell As Integer
    nextCell = Val(LastColumn) + Val(1)

    lastColName = Replace(Replace(Cells(1, nextCell).Address, "1", ""), "$", "")
    Workbooks(sourceFile).Worksheets(Worksheet).Range(lastColName & 1).Value = "New Header"
    MsgBox "New Column has been added : [ " & lastColName & 1 & "]"
End Sub

我可以添加一个带有一些标题的新列,但上面用于向新列添加值的逻辑不起作用。任何人都可以帮助我。 谢谢你的时间!

2 个答案:

答案 0 :(得分:1)

Sub sbInsertingColumns(sourceFile As String, Worksheet As String)

    Dim sht As Worksheet
    Set sht = Workbooks(sourceFile).Worksheets(Worksheet)

    With sht.Range("A1").End(xlToRight).Offset(0, 1)
        Application.Intersect(sht.UsedRange.EntireRow, .EntireColumn).Value = "Cool !"
        .Value = "New Header"
    End With

End Sub

答案 1 :(得分:1)

我会像下面这样说:

Sub sbInsertingColumns(sourceFile As String, sheetName As String, headerName As String)
    With Workbooks(sourceFile).Worksheets(sheetName).UsedRange
        With .Columns(.Columns.Count).Offset(, 1)
            .Value = "Cool !"
            .Cells(1, 1) = headerName
        End With
    End With
End Sub

由一些“main”子使用如下:

Sub main()
    sbInsertingColumns ActiveWorkbook.Name, ActiveSheet.Name, "newheader"
End Sub

您还可以按如下方式缩短参数列表:

Sub sbInsertingColumns(ws As Worksheet, headerName As String)
    With ws.UsedRange
        With .Columns(.Columns.Count).Offset(, 1)
            .Value = "Cool"
            .Cells(1, 1) = headerName
        End With
    End With
End Sub

并将其称为如下

Sub main()
    sbInsertingColumns ActiveSheet, "newheader"
End Sub