Excel VBA range的变量引用问题

tiffany25 2017-12-11 09:42:22
在excel里面编辑了如下代码,可以顺利运行
Sub de()
Dim i As Integer, a As Integer, b As Integer, c As Integer, rn As Range, d As Integer
a = Sheets("Jan").Application.CountA(Range("a:a"))
For i = 1 To 3
Application.Sheets.Add(, Sheets("Jan")).Name = i & "yue"
Sheets("Jan").Range("a1:b1").Copy Sheets(i & "yue").Cells(1, 1)
For Each rn In Sheets("Jan").Range("a1:a10")
If rn = i & "yue" Then
c = Sheets(i & "yue").UsedRange.Rows.Count
Sheets("Jan").Range("a" & rn.Row & ":b" & rn.Row).Copy Sheets(i & "yue").Cells(1, 1).Offset(c)
End If
Next
Next
End Sub
但是修改成下列代码之后(基本只修改了红色的两行),就无法运行(运行到红色的两行excel都会自动提错),但照理来说range的变量引用是可以用cell来代替的啊?为什么无法运行呢?
Sub de()
Dim i As Integer, m As Integer, n As Integer, c As Integer, rn As Range, d As Integer
m = Sheets("Jan").Application.CountA(Range("a:a"))
n = Sheets("Jan").Application.CountA(Range("1:1"))
For i = 1 To 3
Application.Sheets.Add(, Sheets("Jan")).Name = i & "yue"
Sheets("Jan").Range("a1:b1").Copy Sheets(i & "yue").Cells(1, 1)
For Each rn In Sheets("Jan").Range(cells(1,1), cells(m,n))
If rn = i & "yue" Then
c = Sheets(i & "yue").UsedRange.Rows.Count
Sheets("Jan").Range(Cells(c, 1), Cells(c, 2)).Copy Sheets(i & "yue").Cells(1, 1).Offset(c)
End If
Next
Next
End Sub
...全文
4098 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
coychae 2018-03-10
  • 打赏
  • 举报
回复 1
改成 Sheets("Jan").Range(cells(1,1).address, cells(m,n).address) 试试
greatbody 2017-12-17
  • 打赏
  • 举报
回复
提问的人没声音了。
舉杯邀明月 2017-12-15
  • 打赏
  • 举报
回复
具体错误信息是什么啊! 不说清楚…… For Each语句中,In关键字后面应该给出一个“集合对象”吧!  而Sheets("Jan").Range(cells(1,1), cells(m,n))只是表示“一个区域”的单一对象,而不是“集合”,用在那儿肯定不合法。 那个Copy ,改成这样的试试: Sheets("Jan").Range(Cells(c, 1), Cells(c, 2)).Copy Sheets(i & "yue").Cells(1, 1)
赵4老师 2017-12-15
  • 打赏
  • 举报
回复
注释掉所有On Error Resume Next语句,在VBA IDE中运行, 出错后点击调试,光标会停在出错的那条语句处, 或者 事先在怀疑可能有逻辑错误的语句处设置断点,运行经过断点时中断, 此时可以在立即窗口中使用 ?变量名 或 ?函数名(函数参数) 或 过程名(参数) 辅助调试。
shw014 2017-12-15
  • 打赏
  • 举报
回复
For Each rn In Sheets("Jan").Range(cells(1,1), cells(m,n)) 改成 For Each rn In Sheets("Jan").Range(Sheets("Jan").cells(1,1), Sheets("Jan").cells(m,n))
tiffany25 2017-12-12
  • 打赏
  • 举报
回复
用debug.print验证了m和n的值没错。。。。所以才比较纠结~~
赵4老师 2017-12-12
  • 打赏
  • 举报
回复
m和n的值出了问题?

2,461

社区成员

发帖
与我相关
我的任务
社区描述
VBA(Visual Basic for Applications)是Visual Basic的一种宏语言,是在其桌面应用程序中执行通用的自动化(OLE)任务的编程语言。
社区管理员
  • VBA
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧