简体   繁体   English

Sub test() Dim z As String For z = 14 To 17 For b = 14 To 17 ActiveSheet.Cells(b, 13) = "z" Next z Next b End Sub

[英]Sub test() Dim z As String For z = 14 To 17 For b = 14 To 17 ActiveSheet.Cells(b, 13) = "z" Next z Next b End Sub

I am new to VBA and am quite the noob.我是 VBA 的新手,而且是个菜鸟。 I am trying to get a variable to work within quotation marks while looping.我试图让一个变量在循环时在引号内工作。 For example:例如:

Sub test()
Dim z As String
For z = 14 To 17
For b = 14 To 17

ActiveSheet.Cells(b, 13) = "z"

Next z
Next b

End Sub

I get a "Compile error: Type mismatch".我收到“编译错误:类型不匹配”。 Can someone tell me what I am doing wrong?有人能告诉我我做错了什么吗? Thanks for you help.谢谢你的帮助。

You declare the variable z as a string.您将变量z声明为字符串。 Strings are not numbers and cannot be incremented or used in for loops.字符串不是数字,不能在for循环中递增或使用。

Declare the variable as an integer and print the value into the cell.将变量声明为整数并将值打印到单元格中。

The outer z loop is closed before the inner b loop.外部 z 循环在内部 b 循环之前关闭。 That is a problem, too.这也是个问题。 You may want to get used to indenting your code to make such errors more apparent.您可能希望习惯于缩进代码以使此类错误更加明显。

Overall, it is not clear what you want to achieve.总体而言,目前尚不清楚您想要实现的目标。 If you just want to print the z value into a range you don't need the b loop at all, for example:如果您只想将 z 值打印到一个范围内,则根本不需要 b 循环,例如:

Sub test()
Dim z As Integer

For z = 14 To 17
' enters z value into column M
    ActiveSheet.Cells(z, 13) = z
Next z

End Sub

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM