Populating Cells With text in Excel using VBA

时间:2016-07-11 19:47:54

标签: excel vba excel-vba

I am writing a vba script that selects a necessary value from one sheet and puts it in a cell on a different sheet. My current script will determine the proper value but I cannot get the value into the sheet. This function always returns the !Value error. The code breaks on the 6th line of the following excerpt:

Function PrintTest(Cell)
Dim iRow As Integer
Dim bs As Worksheet
Set bs = ThisWorkbook.Sheets("By System")
iRow = Cell.Row
bs.Cells(iRow, 6).Value = "Hello World"
End Function

I have also tried using .Text but that did not work either. Any help would be appreciated.

Note: In the actual Script the text will be seeded from the other sheet and I have it stored in a variable. I am not looking for a way to get the same text into many different cells.

Update: I forgot to mention, Cell is being passed from an Excel spreadsheet as an empty cell G4. Row is defined as 4. Also, not sure if this helps but to call the functions I have been typing "=PrintTest(G4)" in my Excel worksheet named "By System"

Update 2: Scott Holtzman answered the question in a comment. For those who are curious, You cannot write to cells from a UDF called from within a cell. The fix was to call it from a button.

1 个答案:

答案 0 :(得分:0)

Set a cell value with Cells(Row, Col).Value="Some text" If your sheet is active you do not need to fully qualify the address. If you activate the sheet you can just use Cells all of the time. If you have to retrieve data from a different sheet then you will have to qualify the address with the sheet name, i.e. Sheets("My Sheet").Cells(Row, Col).Value.

Also your code has Row=Cell.Row, but you are not saying what cell is active. In that case you are getting some arbitrary value. So that is where your error is, probably. Cell.Row=????? Also Row is an excel word. Use something like intRow for your variable. For example intRow=25. Cells(intRow, 6).Value="My Cell". If the cursor is on a cell you can say intRow=ActiveCell.Row.

When you have a problem such as this set a break point in your code (in your example, the Set statement). Thenm run your code. When it stops at the set statement you can hit F8 to step through one line at a time and examine your variables. Then you will see if Row is really a number or just garbage.

Hope that helps