与VBA代码问题,增加了一个公式与细胞参照其他工作表

问题描述 投票:0回答:1

当用户窗体按钮被点击下面的代码运行时,有一个与最后三行代码,有事做的Locations变量的错误。

该代码必须创建一个名称的新工作表由用户输入,并添加数据一行到“位置”工作表中的新位置,费用在新创建的工作表和费用的总和为每个人的总和的名字新创建的工作表

Private Sub CommandButton1_Click()

Set Locations = ThisWorkbook.Sheets("Locations")

Dim LastRow As Long
Dim Location As String

Location = TextBox1().Value

If Len(Trim(Location)) = 0 Then
    MsgBox "Please enter a location"
Else
    Dim ws As Worksheet
    With ThisWorkbook
    Set ws = .Sheets.Add(After:=.Sheets(.Sheets.Count))
    ws.Name = Location
    Range("A1").Value = "Type"
    Range("B1").Value = "Paid By"
    Range("C1").Value = "Amount"
    End With

    LastRow = Worksheets("Locations").Range("A" & Rows.Count).End(xlUp).Row + 1

    Worksheets("Locations").Range("A" & LastRow).Value = Location
    Worksheets("Locations").Range("B" & LastRow).Formula = "=SUM(" & Location & "!C:C)"
    Worksheets("Locations").Range("C" & LastRow).Formula = "=SUMIF(" & Location & "!B:B;Locations!C2;" & Location & "!C:C)"
    Worksheets("Locations").Range("D" & LastRow).Formula = "=SUMIF(" & Location & "!$B:$B;Locations!D2;" & Location & "!$C:$C)"

End If

End Sub
excel vba
1个回答
0
投票
  • 如果有任何机会,你的工作表名称有空格,那么你需要引用他们在您的公式
  • 当创建在VBA公式列表分隔始终是一个逗号(除非你使用FormulaLocal时,你可以用你的本地列表分隔,但由于种种原因,这不是一个好主意)

未经测试:

Private Sub CommandButton1_Click()

    Dim LastRow As Long
    Dim Location As String
    Dim ws As Worksheet, Locations As Worksheet

    Set Locations = ThisWorkbook.Sheets("Locations")
    Location = Trim(TextBox1.Value)

    If Len(Location) = 0 Then
        MsgBox "Please enter a location"
    Else

        With ThisWorkbook
            Set ws = .Sheets.Add(After:=.Sheets(.Sheets.Count))
        End With
        ws.Name = Location
        ws.Range("A1").Value = "Type"
        ws.Range("B1").Value = "Paid By"
        ws.Range("C1").Value = "Amount"


        With Locations.Range("A" & Rows.Count).End(xlUp).Offset(1, 0).EntireRow
            .Cells(1).Value = Location
            .Cells(2).Formula = "=SUM('" & Location & "'!C:C)"
            .Cells(3).Formula = "=SUMIF('" & Location & "'!B:B,Locations!C2,'" & Location & "'!C:C)"
            .Cells(4).Formula = "=SUMIF('" & Location & "'!$B:$B,Locations!D2,'" & Location & "'!$C:$C)"
        End With
    End If

End Sub
© www.soinside.com 2019 - 2024. All rights reserved.