VBA excel无法在创建后为新工作表中的单元格设置值

cyej8jka  于 2023-01-03  发布在  其他
关注(0)|答案(2)|浏览(150)

我创建了一个新工作表,但我无法在循环中设置新工作表中的单元格值。

Dim dueWs As Worksheet

Sub CreateDue()
Dim i, intsal As Integer
Dim firstDue As String

Set dueWs = Sheets.Add
dueWs.Name = "Due date Table"

firstDue = Range("B11").Value
instal = Range("B7").Value

With dueWs
    .Range("A1").Value = "Instalment"
    .Range("B1").Value = "Due date"

    For i = 1 To instal
        .Range("A" & i + 1).Value = i
        .Range("B" & i + 1).Value = firstDue
        firstDue = DateAdd("m", 1, firstDue)
    Next i
End With

End Sub
nue99wik

nue99wik1#

创建顺序列表

  • 使用Option Explicit,它会强制你声明所有变量。它会警告你关于 "intsal" 的错别字。
  • 当在一行中声明多个变量时,每个变量都必须有一个As子句,否则将声明为As Variant,例如:

Dim i As Long, Instal As Long, firstDue As Date.

  • 每个工作表都有一个工作簿,因此请参考它并使用它来限定工作表,例如

Set ws = wb.Sheets(...).

  • 每个范围都有一个工作表,因此请参考它并使用它来限定范围,例如

Set rg = ws.Range(...).

  • 这不是一个大问题,但是您可以使用一个语句来编写循环中的最后两行:

.Range("B" & i + 1).Value = DateAdd("m", i - 1, firstDue).

Option Explicit

Sub CreateDue()

    Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code

    Dim unoWs As Worksheet: Set unoWs = wb.Sheets("You know its name")

    Dim Instal As Long, firstDue As Date
    
    With unoWs
        Instal = .Range("B7").Value
        firstDue = .Range("B11").Value
    End With

    Dim dueWs As Worksheet: Set dueWs = Sheets.Add

    Dim i As Long
    
    With dueWs
        .Name = "Due date Table"

        .Range("A1").Value = "Instalment"
        .Range("B1").Value = "Due date"

        For i = 1 To Instal
            .Range("A" & i + 1).Value = i
            .Range("B" & i + 1).Value = firstDue
            firstDue = DateAdd("m", 1, firstDue)
        Next i
    
        .Columns("A:B").AutoFit
    End With

    MsgBox "Due date table created.", vbInformation
 
End Sub
mm5n2pyu

mm5n2pyu2#

在我的评论中说了什么,你也可以避免循环:

Option Explicit

Sub CreateDue()

    Dim mainSh As Worksheet
        Set mainSh = ActiveSheet ' change 'ActiveSheet' to your actual "main" data worksheet
    
    With Sheets.Add ' add and reference a new sheet
    
        .Name = "Due date Table" ' name the referenced sheet

        .Range("A1:B1").Value = Array("Instalment", "Due date") ' write range A1:B1 of the referenced sheet

        With .Range("A2").Resize(mainSh.Range("B7").Value, 2) ' reference a range in the referenced sheet starting from A2 with two columns and as many rows as per "main" sheet cell B7 value
            .Columns(1).FormulaR1C1 = "=ROW()-1 ' write the first column of the referenced range"
            .Columns(2).FormulaR1C1 = "=" & mainSh.Name & "!R11C2 +RC[-1]-1" ' write the second column of the referenced range"
            .Value = .Value ' leave only values in the referenced range
        End With
    
    End With
 
End Sub

相关问题