简体   繁体   English

基于FOR循环索引的单元格引用

[英]Cell reference based on FOR loop index

Here is some of my code: 这是我的一些代码:

Dim wbX As Workbook
Dim wbY As Workbook
Set wbX = Application.Workbooks.Open("C:\Converter\aaa.xls")
Set wbY = Application.Workbooks.Open("C:\Converter\bbb.xlsx")

For i = 1 To wbX.Sheets.Count
wbY.Sheets(1).Activate
Range("Y" & i + 2).Select
ActiveSheet.Range("Y" & i + 2).Formula = "=RIGHT(("S" & i + 2); 4)"

The problem is that ("S" & i + 2) is not recognized as a cell - VBA spits out syntax errors. 问题在于(“ S”&i + 2)无法识别为单元格-VBA吐出语法错误。

Maybe this example helps you: 也许这个例子可以帮助您:

Option Explicit

Sub test()
    Dim rngC As Range
    For Each rngC In Range("C2:C100")
        rngC.Offset(0, 4) = Right(rngC, 4)
    Next
End Sub

Your expression "Y" & i + 2 does not yield a valid cell reference because you concatenate a number to a string. 由于将数字连接到字符串,因此表达式"Y" & i + 2不会产生有效的单元格引用。 You must convert the numeric expression to a string: 您必须将数字表达式转换为字符串:

"Y" & Str(i + 2)

What I understand from your comment, the assignment should be written as: 从您的评论中我了解到,作业应写为:

"=LEFT(S" & Trim(Str(i + 2)) & "; 4)"    ' yields e.g.: =LEFT(S3; 4)

(The LEFT function gets the first characters from a string. This assumes the cells you reference contains strings, or that VB converts the value to a string first. And here you must use Trim(Str(i + 2)) because you are constructing a string to place as a formula in the cell.) (LEFT函数从字符串中获取一个字符。这假设您引用的单元格包含字符串,或者VB首先将值转换为字符串。在这里,您必须使用Trim(Str(i + 2))因为您正在构造在公式中放入单元格的字符串。)

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

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