时间:2016-08-17 12:30:02

标签: excel vba replace constants

一直在学习VBA,并且已经帮助了我正在进行的项目10倍。

我遇到了麻烦。

现在我目前有一个“模板表”,里面有公式。

它看起来像这样:

Name
Date  Revenue   Cost  profit  margin
8/08  $10,000   $5000 $5000   100%

Total xxx       xxx    xxx

因此,当我有一个新名称要添加时,我复制整个“模板表”并将其粘贴到最后使用的单元格下面(我循环查找最后一个单元格,因此将其标记为endRow)。在8/08日期行(收入/成本)中,我有一个间接公式,所以我在工作表名称8/08中查找“名称”(我将工作表命名为日期)。

我需要保持'名称'不变,因此整个盒子的价格为20澳元。当我添加新日期时,它会保留20美元,而其他公式会随着我插入日期而改变(IE将日期直接引用到左侧)。

这是我一直在做的更换公式。唯一的问题是,如果我的模板在单元格$ A $ 9中,我将替换9替换为25,如果日期选项卡的公式为19,则将19更改为125.所以它将所有9更改为25.我只是想改变$ A $ fn的公式,但是我做错了。

fn = my for循环以发现模板框的位置。所以我用我粘贴的新单元格替换原始公式

Range(Cells(endRow + 2, 2), Cells(endRow + 2, 7)).Replace What:=fn,    Replacement:=endRow, SearchOrder:=xlByColumns, MatchCase:=True

所以问题是,如何将$ A $ x(x是单元格#)更改为$ A $ y(新单元格#)而不是触及Ax。

    For fn = 1 To 10000
    Set networkCell = Cells(fn, 1)
        If networkCell.Value = "New Station Template" Then
            Range(Cells(fn, 1), Cells(fn + 5, 10)).Copy
            Range(Cells(endRow, 1), Cells(endRow + 5, 10)).Select
            ActiveSheet.Paste
            Cells(endRow, 1).Value = "New Station"
            Range(Cells(endRow + 2, 2), Cells(endRow + 2, 7)).Replace What:=fn, Replacement:=endRow, SearchOrder:=xlByColumns, MatchCase:=True
            count = count + 1
            Exit For
        End If
    Next

1 个答案:

答案 0 :(得分:0)

添加一个新变量以将约束$ A $组合到单元格#,与尝试在替换代码中组合$ A $和单元格#相比似乎有效。

    For fn = 1 To 10000
    Set networkCell = Cells(fn, 1)
        If networkCell.Value = "New Station Template" Then
            Range(Cells(fn, 1), Cells(fn + 5, 10)).Copy
            Range(Cells(endRow, 1), Cells(endRow + 5, 10)).Select
            ActiveSheet.Paste
            Cells(endRow, 1).Value = "New Station"
            oldForm = “$A$” & fn
            newForm = “$A$” & endRow
            Range(Cells(endRow + 2, 2), Cells(endRow + 2, 7)).Replace What:= oldForm, Replacement:= newForm,  SearchOrder:=xlByColumns, MatchCase:=True

            count = count + 1
            Exit For
        End If
    Next