简要问题

时间:2015-02-05 09:58:44

标签: excel vba

我创建了一个宏,可以为我打开和编辑工作簿。它在列(A)中添加,然后格式化单元格A1,B1,C1和D1的标题。

在此之后,我想在每个A单元格中添加相同的日期条件,如果在B列中的相应单元格中有文本 - RC [1]。

有人知道宏应该是什么(Wkb.Worksheets("Sheet1").Range("A1:A250") = "31/12/2014"),还是我完全错了?

也许我需要一个循环?

Sub test()
    Dim MyPath          As String
    Dim MyFile          As String
    Dim Wkb             As Workbook
    Dim Cnt             As Long

    Application.ScreenUpdating = False

    'MyPath = "G:\SHARED\Style Research\Portfolios - Macro Test"
    MyPath = Range("D6").Value

    If Right(MyPath, 1) <> "\" Then MyPath = MyPath & "\"

    MyFile = Dir(MyPath & "*.xls")

    Cnt = 0
    Do While Len(MyFile) > 0
        Cnt = Cnt + 1
        Set Wkb = Workbooks.Open(MyPath & MyFile)
        Wkb.Worksheets("Sheet1").Range("A1").EntireColumn.Insert
        Wkb.Worksheets("Sheet1").Range("A1:A250") = "31/12/2014"
        'Wkb.Worksheets("Sheet1").Range("A1").EntireColumn.NumberFormat = "DD/MM/YYYY"
        Wkb.Worksheets("Sheet1").Range("A1") = "Date"
        Wkb.Worksheets("Sheet1").Range("B1") = "Identifier"
        Wkb.Worksheets("Sheet1").Range("C1") = "Name"
        Wkb.Worksheets("Sheet1").Range("D1") = "%"

        Wkb.Close savechanges:=True
        MyFile = Dir
    Loop

    If Cnt > 0 Then
        MsgBox "Finito", vbExclamation
    Else
        MsgBox "Error!", vbExclamation
    End If

    Application.ScreenUpdating = True
End Sub

1 个答案:

答案 0 :(得分:1)

循环会为你做。

替换

 Wkb.Worksheets("Sheet1").Range("A1:A250") = "31/12/2014"

Dim i as Integer
For i = 1 To 250
    Dim r As Range
    Set r =  Wkb.Worksheets("Sheet1").Range("B" & i, "RC" & i)
    For Each Cell In r.Cells
        If Cell.Value <> "" Then
            Wkb.Worksheets("Sheet1").Range("A" & i).Value = "31/12/2014"
            Exit For
        End If
    Next
Next

以下代码基本上从1循环到250.我是计数器 对于每个i增量,代码将检查所需范围For Each Cell中的每个单元格(B-RC[i])。

如果单元格值不为空,则会将日期添加到相应的Range("A"&i),然后停止查找所需范围内的值,使用Exit For退出并继续到下一个i