用公式填充范围

时间:2019-04-25 07:49:29

标签: excel vba

我想输入一些必须像这样的公式

sheet3.a1.value = "=sheet2!a1=Sheet1!a1"

我正在尝试通过使用静态值的VBA实现这一目标

请找到以下代码

Sub test()
    Dim RowValue, ColumnValue As String

    RowValue = InputBox("Enter Row Number")
    ColumnValue = InputBox("Enter Column Number")

    RangeValue = RowValue + ColumnValue

    Sheet3.Range("A1:" & RangeValue).Value = "=Data1!" & "Range" & "=Data2!" & "Range"
End Sub

4 个答案:

答案 0 :(得分:1)

请勿使用InputBox。使用Application.InputBox。让您指定Type:=

这是您要尝试的(未经测试)吗?

Sub test()
    Dim RowValue As Long, ColumnValue As String
    Dim rng As Range

    '<~~ Type:=1 ==> Numeric Value
    RowValue = Application.InputBox(Prompt:="Enter Row Number", Type:=1) 

    '<~~ Type:=2 ==> TextValue
    ColumnValue = Application.InputBox(Prompt:="Enter Column Number", Type:=2) 

    '~~> Check if the user entered valid values
    On Error Resume Next
    Set rng = Range(ColumnValue & RowValue)
    On Error GoTo 0

    If rng Is Nothing Then
        MsgBox "Wrong parameters specified"
        Exit Sub
    End If

    Sheet3.Range("A1:" & rng.Address).Formula = "=Data1!" & _
                                                rng.Address & _
                                                "=Data2!" & rng.Address

End Sub

答案 1 :(得分:0)

如果要用公式填充范围,则相对(不是绝对)公式将相对于其原始位置调整公式。

Sub test()

    Dim RowValue as LONG, ColumnValue As String, RangeValue As String

    RowValue = InputBox("Enter Row Number")
    ColumnValue = InputBox("Enter Column LETTER")
    RangeValue = ColumnValue & RowValue 

    Sheet3.Range("A1:" & RangeValue).FORMULA = "=Data1!A1=Data2!A1"

End Sub

答案 2 :(得分:0)

您可以尝试:

Option Explicit

Sub test()

    Dim RowValue As Long, ColumnValue As Long, RangeValue As Long

    RowValue = InputBox("Enter Row Number")

    ColumnValue = InputBox("Enter Column Number")

    Sheet3.Range(Cells(1, 1), Cells(RowValue, ColumnValue)).Formula = "=Data1!A1=Data2!A1"

End Sub

答案 3 :(得分:0)

以下代码将查询行和列号,并在所需的单元格中输入硬编码的字符串:

Sub test()
    Dim RowValue, ColumnValue As Long
    Dim RangeValue As String

    RowValue = InputBox("Enter Row Number")
    ColumnValue = InputBox("Enter Column Number")

    Worksheets("Sheet3").Cells(RowValue, ColumnValue).Value = "=Data1!" & "Range" & "=Data2!" & "Range"
End Sub