最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Excel VBA not inputting value from one range into another range - Stack Overflow

programmeradmin4浏览0评论

The below code will not work when i = 1, but works for all remaining values. I have validated there is a value in columns AU & J for i = 1.

If i < 10 Then

 For j = 2 To effCountC
  MSI = Range("AU" & j).Value
  Worksheets("SN" & i).Range("A" & j).Value = "X000" & i & "_" & MSI
 Next j

Else

 For j = 2 To effCountC
  Worksheets("SN" & i).Range("A" & j).Value = "X00" & i & "_" & Range("AU" & j).Value
 Next j

End If

I would like to understand why this code does not work for the first iteration.

I have tried using stops to validate that Excel was reading the values in Column AU, and it appears to be doing so. For some reason, however, the value does not get printed to Column A. Only the first part (X000i_) prints to Column A. However, when i > 1, Excel prints the desired value (X000i_MSI).

The below code will not work when i = 1, but works for all remaining values. I have validated there is a value in columns AU & J for i = 1.

If i < 10 Then

 For j = 2 To effCountC
  MSI = Range("AU" & j).Value
  Worksheets("SN" & i).Range("A" & j).Value = "X000" & i & "_" & MSI
 Next j

Else

 For j = 2 To effCountC
  Worksheets("SN" & i).Range("A" & j).Value = "X00" & i & "_" & Range("AU" & j).Value
 Next j

End If

I would like to understand why this code does not work for the first iteration.

I have tried using stops to validate that Excel was reading the values in Column AU, and it appears to be doing so. For some reason, however, the value does not get printed to Column A. Only the first part (X000i_) prints to Column A. However, when i > 1, Excel prints the desired value (X000i_MSI).

Share Improve this question edited 18 hours ago Chait 1,2872 gold badges22 silver badges36 bronze badges asked Feb 14 at 19:15 Daniel BradleyDaniel Bradley 1 1
  • 2 Some of your ranges don't have a sheet and are defaulting to the active sheet. That is most likely the issue. – Warcupine Commented Feb 14 at 19:32
Add a comment  | 

1 Answer 1

Reset to default 0

This can be simpler as:

For j = 2 To effCountC
    MSI = Range("AU" & j).Value '<< you need to specify a worksheet here...
    Worksheets("SN" & i).Range("A" & j).Value = Format(i, "X0000") & "_" & MSI
Next j

For more on specifying specific worksheets (and workbooks) in your code, there's some useful reading here:

How to avoid using Select in Excel VBA?

Following the advice there will help you avoid most of the common bugs people encounter when getting started with VBA in Excel.

发布评论

评论列表(0)

  1. 暂无评论