【问题标题】:Issue Creating Autofill Macro with a VBA Function使用 VBA 函数创建自动填充宏的问题
【发布时间】:2015-02-18 23:10:38
【问题描述】:

我在创建将自动填充名为“FindMyOrderNumber”的 VBA 函数的宏时遇到问题。每次我运行宏来自动填充“FindMyOrderNumber”时,只会填充列中的第一个单元格。

此函数将在 A (A1) 列中查找订单号,并返回 B (B1) 中可以找到的工作表的名称。

Option Explicit
Function FindMyOrderNumber(strOrder As String) As String

    Dim ws As Worksheet
    Dim rng As Range

    For Each ws In Worksheets
        If ws.CodeName <> "Sheet3" Then
            Set rng = Nothing
            On Error Resume Next
                Set rng = ws.Cells.Find(What:=strOrder, LookAt:=xlWhole)
            On Error GoTo 0
            If Not rng Is Nothing Then
                FindMyOrderNumber = ws.Name
                Exit For
            End If
        End If
    Next

    Set rng = Nothing
    Set ws = Nothing

End Function

我创建这个宏是为了在单元格 B1 中输入我的 VBA 函数“=findmyordernumber(a1)”,然后输入到自动填充列 B。

Sub AutofillVBAFunction()

    Range("B1").Select
    ActiveCell.FormulaR1C1 = "=FindMyOrderNumber(RC[-1])"
    Selection.Autofill Destination:=Range("B1:B68")
    Range("B1:B68").Select
End Sub

运行此宏后,仅填充 B1。

抱歉,如果已经讨论过这个问题,我是新手,我尝试了 How to fill-up cells within a Excel worksheet from a VBA function? 和其他问题,但无法将其应用于我的问题。

请帮忙

【问题讨论】:

  • Range("B1:B68")="=FindMyOrderNumber(RC[-1])" 试试看。

标签: vba excel


【解决方案1】:

将 application.volatile 添加到函数中,这样它就会随着工作表的变化而计算。

Function FindMyOrderNumber(strOrder As String) As String

    Dim ws As Worksheet
    Dim rng As Range
    Application.Volatile
    For Each ws In Worksheets
        If ws.CodeName <> "Sheet3" Then
            Set rng = Nothing
            On Error Resume Next
            Set rng = ws.Cells.Find(What:=strOrder, LookAt:=xlWhole)
            On Error GoTo 0
            If Not rng Is Nothing Then
                FindMyOrderNumber = ws.Name
                Exit For
            End If
        End If
    Next

    Set rng = Nothing
    Set ws = Nothing

End Function

当您将公式添加到范围时,计算工作表也不会受到伤害。

Sub Button1_Click()
    Dim Rws As Long, Rng As Range
    Rws = Cells(Rows.Count, "A").End(xlUp).Row
    Set Rng = Range(Cells(1, 2), Cells(Rws, 2))
    Rng = "=FindMyOrderNumber(RC[-1])"
End Sub

【讨论】:

  • 我现在遇到的问题是,随着时间的推移,我尝试使用 A 列会变大: Range("B:B") = "=FindMyOrderNumber(RC[-1])" -覆盖我的基地,但我的 Excel 会崩溃。
  • 你太棒了!非常感谢。
猜你喜欢
  • 2022-06-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-07
  • 2018-09-04
  • 1970-01-01
  • 1970-01-01
  • 2016-02-20
相关资源
最近更新 更多