excel - 使用用户选择的单元格范围
问题描述
我正在编写代码以将工作表复制并粘贴到同一工作簿中给定的次数,同时每次将日期增加一天。当我在代码中输入想要增加自我的范围时,我可以这样做,但是一旦我尝试使用用户选择的范围 - 我得到错误 1004。
任何帮助将非常感激
这是我的代码:
Sub IncrementWorksheets()
Dim ws As Worksheet
Dim Count As Integer
Dim Rng As Range
Dim myValue As Integer
'User input for increment value
Set Rng = Application.InputBox( _
Title:="Increment your worksheet", _
Prompt:="Select a cell you want to increment", _
Type:=8)
On Error GoTo
'Test to ensure User Did not cancel
If Rng Is Nothing Then Exit Sub
'Set Variable to first cell in user's input (ensuring only 1 cell)
Set Rng = Rng.Cells(1, 1)
MsgBox Rng.Value
myValue = InputBox("How many time do you want it to increment? Give me the number ")
Do While Count < myValue
For Each ws In Worksheets
LastWs = ws.Name
'i = ws.Range("C3").Value >> code works when i type in cell value
'>>>>The error occurs here " 1004 Application-defined or Object-defined error
i = ws.Range("Rng").Value
If i > j Then
j = i
End If
Next
Sheets(2).Select
Sheets(2).Copy After:=Sheets(LastWs)
'ActiveSheet.Range("C3").Value = j + 1 >> code works when i type in cell value
ActiveSheet.Range("Rng").Value = j + 1
Count = Count + 1
Loop
End Sub
解决方案
使用 Rng.Address,而不是“Rng”。
Sub IncrementWorksheets()
Dim ws As Worksheet
Dim Count As Integer
Dim Rng As Range
Dim myValue As Integer
'User input for increment value
Set Rng = Application.InputBox( _
Title:="Increment your worksheet", _
Prompt:="Select a cell you want to increment", _
Type:=8)
'Test to ensure User Did not cancel
If Rng Is Nothing Then Exit Sub
'Set Variable to first cell in user's input (ensuring only 1 cell)
Set Rng = Rng.Cells(1, 1)
MsgBox Rng.Value
myValue = InputBox("How many time do you want it to increment? Give me the number ")
Do While Count < myValue
For Each ws In Worksheets
LastWs = ws.Name
'i = ws.Range("C3").Value >> code works when i type in cell value
'>>>>The error occurs here " 1004 Application-defined or Object-defined error
i = ws.Range(Rng.Address).Value
If i > j Then
j = i
End If
Next
Sheets(2).Select
Sheets(2).Copy After:=Sheets(LastWs)
'ActiveSheet.Range("C3").Value = j + 1 >> code works when i type in cell value
ActiveSheet.Range(Rng.Address).Value = j + 1
Count = Count + 1
Loop
End Sub
推荐阅读
- javascript - 过滤复杂对象中的数组数组并返回该对象
- mysql - 未在所有行上执行 LIKE 的 DELETE 查询
- postgresql - 生成 postgres 安装日志
- java - 在控制器级别使用 @RequestMapping 和动态 URL
- powershell - 全局停止作业:作业未定义为 ID 或值
- javascript - Javascript(Typescript)错误处理 - 将父错误类转换为子类
- javascript - 如何使用 React HashRouter 和 Apollo 客户端渲染反应类组件?
- shopify - 为什么所有主题都在更新?shopify 主题套件
- c# - 类属性的 TypeConverter 用法
- c++ - Apache ORC 在读取数据时跳过条纹