Excel VBScript问题,引用关系单元格地址

时间:2015-04-09 17:22:39

标签: excel excel-vba vba

好的,我正在学习Excel的脚本,我遇到了一些我不知道该怎么做的事。

我被要求帮助自动将工作表导入工作表,然后将一些列添加到一边并进行一些计算并将它们自动填充到导入信息的最后一行。那没问题。然而,我最近发现,我要为我的办公室导入的工作表有X个列,而其他办公室在他们要导入的工作表中有Y和Z列数。所以我试图在导入列末尾构建计算列的位置。有了这些背景,我需要一些帮助:

为我的办公室写的脚本和作品:

    Range("O1").Select
    ActiveCell.FormulaR1C1 = "Remainder"
    Range("O2").Select
    ActiveCell.FormulaR1C1 = "=MOD(RC[-14],RC[-5])"
    Range("O2").Select
    Range("O2").AutoFill Destination:=Range("O2:O" & Cells(Rows.Count, "B").End(xlUp).Row)

所以现在我需要使这个关系不是Cell Address Specific所以我提出了这个。

    Range("A1").select
    Selection.End(xlToRight).Select
    ActiveCell.Offset(0, 1).Select
    ActiveCell.FormulaR1C1 = "Threshold"
    ActiveCell.Offset(1, 0).Select
    ActiveCell.FormulaR1C1 = "=IF(RC[-13]>(RC[-5]/3),""Over"",""Under"")"       
    Range(ActiveCell.Address).AutoFill Destination:=Range(*****How to return the Current Cell Address** : **How to Return the Current Column Letter***** & Cells(Rows.Count, "B").End(xlUp).Row)

我试过“ActiveCell.Address”:“CHAR(COLUMN()+ 64))”但这不起作用我只是不知道如何设置该值为等效? 2:?我的办公室运行这个应该从O2:O自动填充。但是会在另一个中返回P2:P。

2 个答案:

答案 0 :(得分:0)

我假设您希望公式进入第一个未使用的列,无论有多少列。 (这也将允许将来使用列。)

Dim LastCol as integer

LastCol = Cells(1, Columns.Count).End(xlToLeft).Column + 1
Cells(1, LastCol).FormulaR1C1 = "Remainder"
Cells(2, LastCol).FormulaR1C1 = "=MOD(RC[-14],RC[-5])"
Cells(2, LastCol).AutoFill Destination:=Range(Cells(2, LastCol), _
      Cells(Cells(Rows.Count, "B").End(xlUp).Row, LastCol))

答案 1 :(得分:0)

这是怎么回事:

Sub test()
Dim lastCol As Integer, lastRow As Integer, formulaCol As Integer
Dim ws As Worksheet

Set ws = ActiveSheet

' First, let's find the last column (#) and last row (#)
With ws.UsedRange
    lastCol = .Columns.Count
    lastRow = .Rows.Count
End With

' Now, create the "header, two columns offset from last column"
formulaCol = lastCol + 2
Cells(1, formulaCol).Value = "Remainder"


'Now, let's create a range, that we will fill with the MOD() formula. You can do this _
through resizing a range, instead of selecting and autofill

With ws
    .Range(.Cells(2, formulaCol), .Cells(2, formulaCol)).Resize(lastRow - 1, 1).FormulaR1C1 = _
        "=IF(RC[-" & formulaCol - 1 & "]>(RC[-2]/3),""Over"",""Under"")"
End With

End Sub

我假设了一些事情:您的原始表单中包含数据。换句话说,您需要的数据之间没有列间距。这将获取最后使用的列和行,并使用它们输入您的公式。

另外,我假设您正在检查mod()公式的第一部分是否引用了Col.A中的信息,第二部分是最右侧列的数据。我想我不理解某些东西,所以更多的信息。关于如何布置数据会有所帮助。但是,这也避免了使用" Select"这是我收集的VBA练习。