简体   繁体   English

在VBA Excel中使用替换公式替换单元格地址

[英]Replace Cell Address using Replace Formula in VBA Excel

I want replace the x input from the user to the Cell Address value that is stored in N2 . 我想将用户输入的x替换为N2存储的单元格地址值。 For example Cells(2, i+10) is J2 Cell, in the first loop in cell A2 it will be =J2^2 if the user wrote x^2 and the next loop would be B2=K^3 if the user wrote x^3 and so on. 例如, Cells(2, i+10)J2 Cell,在单元格A2的第一个循环中,如果用户写了x^2 ,它将是=J2^2如果用户编写了下一个循环,则是B2=K^3 x^3等。

    numero_formulas = InputBox("¿Cuántas fórmulas vas a ingresar?")
    Sheets("ResultadosContinua").range("I6") = numero_formulas

    For i = 1 To numero_formulas

    N2 = Cells(2, i + 10)

    formula_user = InputBox("Escribe la fórmula:" & i & "")
    Cells(2, i).Select
    Sheets("ResultadosContinua").Select
    ActiveCell.Formula = "=" & Replace(formula_user, "x", " & N2 & ")

If you want the address of the N2 , (4 columns away from the activecell) you need you use this: 如果您想要N2的地址(距离活动单元4列),则需要使用以下命令:

numero_formulas = InputBox("¿Cuántas fórmulas vas a ingresar?")
Sheets("ResultadosContinua").Range("I6") = numero_formulas

For i = 1 To numero_formulas

n2 = Cells(2, i + 10)
formula_user = InputBox("Escribe la fórmula:" & i & "")
Cells(2, i).Select
Sheets("ResultadosContinua").Select
ActiveCell.Formula = "=" & Replace(formula_user, "x", ActiveCell.Offset(0, 4).Address(False, False))

But as I said, you code will delete the formula inside the cel N2 , after the 4th iteration. 但是正如我所说,您的代码将在第4次迭代后删除cel N2内部的公式。

I'd suggest reading up on how to avoid using .Select as per this question . 我建议阅读有关如何避免使用.Select ,请按照此问题进行 I would also encourage using the full name of the object you're targeting. 我也鼓励使用您要定位的对象的全名。 ie Cells(2,10) = "Text" will work but it's always better to write Cells(2,10).Value = "Text" . Cells(2,10) = "Text"将起作用,但是编写Cells(2,10).Value = "Text"总是更好。 Your code could then be modified to read: 然后可以将您的代码修改为:

Dim rngNumeroRange as Range
Dim intNumeroFormulas as Integer
Dim rngN2 as Range

Set rngNumeroRange = Sheets("ResultadosContinua").Range("I6")
intNumeroFormulas = InputBox("¿Cuántas fórmulas vas a ingresar?")
rngNumeroRange.Value = intNumeroFormulas 

For i = 1 To intNumeroFormulas 

    set rngN2 = Sheets("ResultadosContinua").Cells(2, i)

    formula_user = InputBox("Escribe la fórmula:" & i & "")
    rngN2.Formula = "=" & Replace(formula_user, "x", rngN2.Offset(0, 9).Address(False, False))

Next

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM