我的代码有麻烦。我需要用一个用户表单更新多张工作表。但是,我的代码不断给我错误。任何帮助,将不胜感激。
Private Sub AddItem_Click()
Dim r As Long
Dim r1 As Long
Dim Sheet1 As Worksheet
Dim Sheet4 As Worksheet
With Worksheets("Sheet1", "Sheet4")
r = .Range("A" & .Rows.Count).End(xlUp).Row + 1
r1 = .Range("A" & .Rows.Count).End(xlUp).Row + 1
.Range("A" & r) = Me.txtFN
.Range("A" & r1) = Me.txtFN
.Range("B" & r) = Me.txtLN
答案 0 :(得分:1)
Worksheets
属性使用一个参数,而不是工作表名称的列表;您需要通过Array(...)
调用来包装工作表名称列表,以使用一个以上的工作表名称来填充它。
With Worksheets(Array("Sheet1", "Sheet4"))
但是这样做只会使Worksheets
调用成功-它仍然不会返回您期望使用的对象。
With
块包含对对象的引用。在这种情况下,对象类为Excel.Sheets
,它是纸的集合。
工作表的集合没有Range
属性;您无法像对待单个Worksheet
一样对待它。
假设您打算将该逻辑应用于集合中的所有Worksheets
对象,则需要遍历该集合中的工作表。
Dim ws As Worksheet
For Each ws In Worksheets(Array("Sheet1", "Sheet4"))
With ws
r = .Range("A" & .Rows.Count).End(xlUp).Row + 1
...
End With
Next
答案 1 :(得分:1)
我还没有测试过,但是尝试像这样
Option Explicit
Sub AddItem_Click()
Dim oWS As Worksheet
Dim iLRow As Long, iC As Long, iErr As Long
Dim aSheets As Variant: aSheets = Array("Sheet1", "Sheet4")
For iC = LBound(aSheets) To UBound(aSheets)
Err.Clear
iErr = 0
On Error Resume Next
Set oWS = ThisWorkbook.Worksheets(aSheets(iC))
iErr = Err.Number
On Error GoTo 0
If iErr = 0 Then
With oWS
iLRow = .Cells(.Rows.Count, 1).End(xlUp).Row + 1
.Range("A" & iLRow) = "Test"
.Range("B" & iLRow) = "Test2"
End With
End If
Next
End Sub