I want to select a value from one sheet and put it in a cell on a different sheet.
My script determines the proper value but I cannot get the value into the sheet.
This function returns the !Value error 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 also tried using .Text.
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: Cell is passed from an Excel spreadsheet as an empty cell G4. Row is defined as 4. 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. You cannot write to cells from a UDF called from within a cell. The fix was to call it from a button.
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
Related
I have a WS named Stats and I want to fill a column with the MINIMUMs. The data is in the same WB, but on another WS called Data.
The data is in rows, so MIN calc would be performed on range B to IQ columns.
And I need to calc the MIN for rows 14 to 1868.
The following code works, but name and range of the data is hard coded:
Worksheets("Stats").Range("B14:B1868").Formula = "=MIN(Data!B58:IQ58)"
So my problem is that every workbook has a different worksheet name for the data. My macro has to work for all WBs.
I've tried the Indirect function, and this configuration only works for one row of data and populates the rest of the column with the same number(note that $A$2 is the location with the Worksheet name that contains the data):
Worksheets("Stats").Range("B14:B1868").Formula = "=MIN(Indirect($A$2&""!B58:IQ58"")"
I have tried so many different configs and can't figure this one out. I'll get a name or a ref error...it's driving me nuts, hoping someone here can help me!
Thanks in advance:-)
You can use a cell reference's value just as easily as a string literal.
(Sense of deja-vu there - I wrote that as part of an answer just this morning!)
So, instead of hard-coding "Data" into the formula
Worksheets("Stats").Range("B14:B1868").Formula = "=MIN(Data!B58:IQ58)"
you can insert the value from a cell
Worksheets("Stats").Range("B14:B1868").Formula = "=MIN('" & Worksheets("Stats").Range("A2").Value & "'!B58:IQ58)"
(I added apostrophes around the sheet name as well, just in case it contained spaces or other special characters.)
I am not very familiar with VBA programming, though I have written a few basic modules. I am having some difficulty in coding the following problem. I would appreciate if someone could show a basic solution.
Problem: I have 3 tabs in an Excel file, "Rack1", "Rack2" and "Rack3". They each have a column called "tag". The tag column contains a code, made up of numerals 0 to 9999 and one letter, A or B.
I want to look up the first "A" code in Rack1, then find the matching "B" code. If the B code is not in tab "Rack1", I want to search tab "Rack2", then "Rack3" if it's not found in either.
After the "B" part is found, I want to have a Msgbox message - "Found in Rack..." OR "B part not found"
Then ... go on to the next A code. Thanks
Please let us know what have you tried so far to get things working at your end.
You may have to loop through with your requirement with all sheets with respective column and its range.
I am not very clear, what is your exact requirement but you can do something like this
declare variables of your sheets
Set sheet1 = Worksheets("Sheet1")
Set sheet2 = Worksheets("Sheet2")
Set sheet3 = Worksheets("Sheet3")
You have to set range as per your need. Now you have to loop your sheet1 and tag column. While searching you need check whether A is exist in respective cell by cell value see below example
If InStr(cell_value, "A") > 0 Then
Meanwhile you can check below post for your further reference.
Excel Looping through rows and copy cell values to another worksheet
I'm running into a (run-time error '1004': Application-defined or object-defined error) error while trying to write my first Excel VBA Macro. I've looked at similar questions on stack overflow and other sites, but my issue seems to be more basic than issues others are having.
Currently, I'm trying to take the data from two cells from one sheet and write them to another sheet. I understand that trying to find the column or row of a cell that I reference by cell or row is unnecessary, but eventually I will use for-loops and will substitute the specific cell references with variables.
Here are the two lines of code that I have:
Worksheets("Sheet2").Range("A1").Value = Worksheets("Sheet1").Range("A" & Worksheets("Sheet1").Range("B2").Row).Value
Worksheets("Sheet2").Range("B1").Value = Worksheets("Sheet1").Range(Worksheets("Sheet1").Range("B2").Column & "1").Value
The first line runs fine. It writes Sheet1's A2 to Sheet2's A1.
The second line does not run, does not write Sheet1's B1 to Sheet2's B1, references the error, and I'm not sure why.
Thank you for your time and help!
The .Columns property returns an integer, not a letter. Use the Range.Cells property if you want to define a range with a numerical row and numerical column.
Worksheets("Sheet2").Range("B1").Value = Worksheets("Sheet1").Cells(1, Range("B2").Column).Value
I suppose there is a larger purpose to this but as it sits, it is very verbose code.
your last lines from your question say that you want to fill Sheet2-A1 with Sheet1-A2 and Sheet2-B1 with Sheet1-B1
the most straightforward way is
Worksheets("Sheet2").Range("A1") = Worksheets("Sheet1").Range("A2")
Worksheets("Sheet2").Range("B1") = Worksheets("Sheet1").Range("B1")
I am a beginner at VBA just like you. You don't need to know everthing in VBA to make productive use of it. I made my first macro by RECORDING it, and it worked (but was hopelessly inefficient).
I had a problem similar to yours: looking up data on another worksheet. I created the following function:
Function GetMyNumber(C3ll)
MyCol = C3ll.Column
GetMyNumber = MyCol
End Function
To use it in a spreadsheet, just enter the formula into some cell, like D5,
=GetMyNumber(D5)
When you recalculate, the number 4 appears in cell D5. If you copy cell D5 into Cell F3, you will see in F3, =GetMyNumber(F3), and calculate will return a 6. Of course you can fill down or across, the argument is changed to the cell the formula is in. And if you want, you can offset with an argument referring to any cell.
Once you get this working, you can insert the code to do you matching and other tasks that make use of your column number MyCol to extract the number from the other worksheet. Remember, MyCol is an integer.
Hopes this helps.
I have a sheet with a lots of columns ordered in a hierarchical way with the cells merged:
I'd like to name those columns (in example: row 5) like this:MainGroupA-SubGroupA-SubSubGroupA.
Simply referencing the columns above in the classic way won't work as the field above isn't available anymore. (In the example: the fields B1 to F1) (i.e. I can't enter A1&A2&A3 / R[-4]C&R[-3]C&R[-2]C as this formula tries to read from the "hidden" cells).
Is there a way to do this without manual work or the need to un-merge the parent-cells? I might be able to do this with some external text editor or even VBA but would prefer an "Excel formula solution" as it would stay updated for new groups and columns.
To Clarify: I'd like all columns in Line 5 to have the text like in A5
If you want:
MainGroupA-SubGroupA-SubSubGroupA
in A5 then this should work:
=A1&"-"&A2&"-"&A3
Edit Then try:
=OFFSET(A1,0,1-MOD(COLUMN(),6))&"-"&OFFSET(A2,0,MOD(COLUMN(),2)-1)&"-"&A3
though this won't give the same text as in A5 across the complete row.
The answer from pnuts is great and helped me solve some test cases. It was however a little difficult to adapt and produced empty strings for the last column, so I also wrote a VBA-Function to do exactly what I need.
Open the VBA Editor (ALT + F11) and enter the following code in a new module:
Public Function checkLeftIfEmpty(start As range) As String
If start.Cells.Count > 1 Then
checkLeftIfEmpty = "Only a single cell allowed as parameter"
Exit Function
End If
Dim currentRange As range
Set currentRange = start
Do While currentRange.Column >= 1
If currentRange.Value <> "" Then
checkLeftIfEmpty = currentRange.Value
Exit Function
Else
Set currentRange = currentRange.Offset(0, -1)
End If
Loop
End Function
You can now use the function checkLeftIfEmpty to find the first cell left-side from your parameter which contains text: (This will be the text of the merged cell itself, if applied to a "hidden by merge" cell)
And also in combination to concatenate a string:
I am writing a quick application myself - first project, however I am trying to find the VBA code for writing the result of an input string to a named cell in Excel.
For example, a input box asks the question "Which job number would you like to add to the list?"... the user would then enter a reference number such as "FX1234356". The macro then needs to write that information into a cell, which I can then use to finish the macro (basically a search in some data).
You can use the Range object in VBA to set the value of a named cell, just like any other cell.
Range("C1").Value = Inputbox("Which job number would you like to add to the list?)
Where "C1" is the name of the cell you want to update.
My Excel VBA is a little bit old and crusty, so there may be a better way to do this in newer versions of Excel.
I recommend always using a named range (as you have suggested you are doing) because if any columns or rows are added or deleted, the name reference will update, whereas if you hard code the cell reference (eg "H1" as suggested in one of the responses) in VBA, then it will not update and will point to the wrong cell.
So
Range("RefNo") = InputBox("....")
is safer than
Range("H1") = InputBox("....")
You can set the value of several cells, too.
Range("Results").Resize(10,3) = arrResults()
where arrResults is an array of at least 10 rows & 3 columns (and can be any type). If you use this, put this
Option Base 1
at the top of the VBA module, otherwise VBA will assume the array starts at 0 and put a blank first row and column in the sheet. This line makes all arrays start at 1 as a default (which may be abnormal in most languages but works well with spreadsheets).
When asking a user for a response to put into a cell using the InputBox method, there are usually three things that can happen¹.
The user types something in and clicks OK. This is what you expect to happen and you will receive input back that can be returned directly to a cell or a declared variable.
The user clicks Cancel, presses Esc or clicks × (Close). The return value is a boolean False. This should be accounted for.
The user does not type anything in but clicks OK regardless. The return value is a zero-length string.
If you are putting the return value into a cell, your own logic stream will dictate what you want to do about the latter two scenarios. You may want to clear the cell or you may want to leave the cell contents alone. Here is how to handle the various outcomes with a variant type variable and a Select Case statement.
Dim returnVal As Variant
returnVal = InputBox(Prompt:="Type a value:", Title:="Test Data")
'if the user clicked Cancel, Close or Esc the False
'is translated to the variant as a vbNullString
Select Case True
Case Len(returnVal) = 0
'no value but user clicked OK - clear the target cell
Range("A2").ClearContents
Case Else
'returned a value with OK, save it
Range("A2") = returnVal
End Select
¹ There is a fourth scenario when a specific type of InputBox method is used. An InputBox can return a formula, cell range error or array. Those are special cases and requires using very specific syntax options. See the supplied link for more.
I've done this kind of thing with a form that contains a TextBox.
So if you wanted to put this in say cell H1, then use:
ActiveSheet.Range("H1").Value = txtBoxName.Text