I am trying to create a macro that brings in the name of the sheet and combine it with text. For example, for sheet one, I want it to say "ThisIs_Sheet1_Test" in I5 of Sheet1. There are several sheets but it should work for all of them.
What is wrong with my code? I think the underscore might be ruining it all. Here's what I have:
Dim SheetName As String
Public Sub CommandButton1_Click()
SheetName = ActiveSheet.Name
Sheets("Sheet1").Range("I5", "I5") = ThisIs_" & SheetName.text & "_Test
Sheets("Sheet2").Range("H5", "H5") = ThisIs_" & SheetName.text & "_Test
Sheets("Sheet3").Range("G5", "G5") = ThisIs_" & SheetName.text & "_Test
End Sub
This question has been forwarded to Pull in Earlier Value Using Concatenation
looks like a quoting problem. ThisIs_ and _Test are strings, right? So the quotes should be around them, not around & SheetName.text &
Sheets("Sheet1").Range("I5", "I5") = "ThisIs_" & SheetName.text & "_Test"
In addition to the missing quotes, SheetName is a string, not an object, so it won't have a Text property. Did you want the name of the sheet to change as the sheet changes? You need this:
Private Sub CommandButton1_Click()
Dim ws As Worksheet
For Each ws In Me.Parent.Worksheets
ws.Range("I5").Value = "ThisIs_" & ws.Name & "_Test"
Next ws
End Sub
I am able to get it to work...sort of.
Now, it displays ThisIS_Sheet1_Test in Sheet1, etc.
However, I have it set up to pull data from a listbox into a function which I called ThisIS_Sheet1_Test. I figured that once I got it to display the name, it would pull the function in. Here's what I have above:
Public Sub ListBox2_LostFocus()
ListBox2.Height = 15
With ListBox2
ThisIS_Sheet1_Test = "'"
For i = 0 To .ListCount - 1
If .Selected(i) Then
ThisIS_Sheet1_Test = ThisIS_Sheet1_Test & .List(i) & "','"
End If
Next i
End With
ThisIS_Sheet1_Test = Left(ThisIS_Sheet1_Test, Len(ThisIS_Sheet1_Test) - 2)
End Sub
How come when I get the text I want it doesn't translate into the function I thought it would.
can you take few minutes to compile your code (in VBA Window, Debug->Compile VBA Project) before looking for other's help?? That would have screamed about your missing quotes, using .Text on a string variable etc.
Public Sub dummy()
Dim SheetName As String
SheetName = ActiveSheet.Name
Sheets("Sheet1").Range("I5", "I5") = "ThisIs_" & SheetName & "_Test"
Sheets("Sheet2").Range("H5", "H5") = "ThisIs_" & SheetName & "_Test"
Sheets("Sheet3").Range("G5", "G5") = "ThisIs_" & SheetName & "_Test"
End Sub
Underscore carries a special meaning in VBA/VB world. Its code concatination (meaning if your code is too long and you want to split it across two lines then you put a space underscore ( _) and continue with next line. And also Dick Kusleika is right about object/string. Only for objects you will have differnt peopreties (.Text means you are asking for Text property of that object), and usually that Text property would be of String type. here you already have a String, and you just use it as it is.
Related
I found a lot of examples but it's not working in my case and I don't know why.
Very basic code:
Sub Test()
Dim namCur As Name
For Each namCur In ActiveSheet.Names
MsgBox "Name: " & namCur.Name & ", Refers To: " & namCur.RefersTo
Next namCur
End Sub
And I have the same issue when I use Worksheets("Assumptions").Names
When I watch ActiveSheet.Name, this is correct I get "Assumptions", you can see on the picture below the list of named ranges. But I never get the MsgBox and the For loop goes directly to the end.
Edit: Very important, I need to loop only this sheet's named ranges, not the whole workbook
Any idea?
I use Excel 2016
Your solution will only list Names that have a scope set to only the ActiveSheet.
Change this
For Each namCur In ActiveSheet.Names
To this
For Each namCur In ThisWorkBook.Names
to list all names in the Workbook. You can then check the RefersTo address to check if it applies to the ActiveSheet.
Sub Test()
Dim namCur As Name
Dim TargetSheetName As String
TargetSheetName = "Assumptions"
For Each namCur In ThisWorkbook.Names
If Range(namCur.RefersTo).Parent.Name = TargetSheetName Then MsgBox "Name: " & namCur.Name & ", Refers To: " & namCur.RefersTo
Next namCur
End Sub
I am quite new in VBA and wrote a subroutine that copy-paste cells from one document into another one. Being more precise, I am working in document 1 where I have names of several product (all in column "A"). For these product, I need to look up certain variables (e.g. sales) in a second document.
The subroutine is doing the job quite nicely, but I want to use it as a funcion, i.e. I want to call the sub by typing in a cell "=functionname(productname)".
I am grateful for any helpful comments!
Best, Andreas
Sub copy_paste_data()
Dim strVerweis As String
Dim Spalte
Dim Zeile
Dim findezelle1 As Range
Dim findezelle2 As Range
Dim Variable
Dim Produkt
'Variable I need to copy from dokument 2
Variable = "frequency"
'Produkt I need to copy data from document 2
Produkt = Cells(ActiveCell.Row, 1)
'path, file and shhet of document 2
Const strPfad = "C:\Users\Desktop\test\"
Const strDatei = "Bezugsdok.xlsx"
Const strBlatt = "post_test"
'open ducument 2
Workbooks.Open strPfad & strDatei
Worksheets(strBlatt).Select
Set findezelle = ActiveSheet.Cells.Find(Variable)
Spalte = Split(findezelle.Address, "$")(1)
Set findezelle2 = ActiveSheet.Cells.Find(Produkt)
Zeile = Split(findezelle2.Address, "$")(2)
'copy cell that I need
strZelle = Spalte & Zeile 'Zelladresse
strVerweis = "'" & strPfad & "[" & strDatei & "]" & strBlatt & "'!" & strZelle
'close document 2
Workbooks(strDatei).Close savechanges:=False
With ActiveCell
.Formula = "=IF(" & strVerweis & "="""",""""," & strVerweis & ")"
.Value = .Value
End With
End Sub
Here is an example to create a function that brings just the first 3 letters of a cell:
Public Function FirstThree(Cell As Range) As String
FirstThree = Left(Cell.Text, 3)
End Function
And using this in a Excel worksheet would be like:
=FirstThree(b1)
If the sub works fine and you just want to make it easier to call you can add a hotkey to execute the Macro. In the developer tab click on Macros then Options. You can then add a shortcut key (Crtl + "the key you want" it can be a shortcut key already used like C, V, S, but you will lose those functions (Copy, Paste Save, Print)
enter image description here
I'm using VBA in Excel and I'm assigning a VLOOKUP as a formula to a cell. It works fine, but I would like to use a variable that refers to the last cell that contains a value in the column.
In the example below, I would the value for $B$269 to change depending on the number of elements in the closed document.
"=VLOOKUP(B2,'Macintosh HD:Users:myself:Documents:[Master_Terms_Users.xlsm]Master_Terms_Users.csv'!$A$1:$B$269,2,FALSE)"
I know I want to use something along the lines of:
Range("B" & Rows.Count).End(xlUp).Address
With that said, I haven't been able to figure out how to incorporate the result, which is something like $B$269 into the VLOOKUP. I know that those formulas return the correct address because I've used it in Debug.Print.
I tried to do something like this:
"=VLOOKUP(B2,'Macintosh HD:Users:myself:Documents:[Master_Terms_Users.xlsm]Master_Terms_Users.csv'!$A$1:"&GetLastRowFunct&",2,FALSE)"
But that didn't work.
Here is my current code:
Sub GetLastRow()
Debug.Print GetLastRowFunct
End Sub
Function GetLastRowFunct() As String
Dim openNwb As Workbook
Const MasterPath = "Macintosh HD:Users:myself:Documents:"
Dim strNewFileName As String
strNewFileName = "Master_Terms_Users.xlsm"
Set openNwb = Workbooks.Open(MasterPath & strNewFileName)
Dim openNws As Worksheet
Set openNws = openNwb.Worksheets(1)
GetLastRowFunct = openNws.Range("B" & Rows.Count).End(xlUp).Address
openNwb.Close
End Function
Any recommendations would be appreciated.
I would rewrite that function to return the entire range address, including worksheet, workbook and path.
Function GetLastRowFunct() As String
Const MasterPath = "Macintosh HD:Users:myself:Documents:"
Dim openNwb As Workbook, strNewFileName As String
strNewFileName = "Master_Terms_Users.xlsm"
Set openNwb = Workbooks.Open(MasterPath & strNewFileName)
with openNwb.Worksheets(1)
GetLastRowFunct = .Range(.cells(1, 1), .cells(rows.count, "B").End(xlUp)).Address(1, 1, external:=true)
end with
openNwb.Close
End Function
The formula construction and assignment becomes simpler to deal with.
rng.formula = "=VLOOKUP(B2, " & GetLastRowFunct & ", 2, FALSE)"
tbh, I'm not sure if you have to supply your own square brackets or not on a Mac.
I'm trying to reference data from another workbook and I found that (correct me if I'm wrong) inserting the worksheet formulas directly into the cells (see code below) is the only way to do this without actually opening the workbook I'm referring to. Now my dilemma is I'm trying to make the directory portion of this code variable such that the user can do something like:
Path = Application.GetOpenFilename
Right now the path is fixed at 'S:\SN\SN\2015-S[2015SNL.xlsx]2015'
Sub Formulation()
Application.ScreenUpdating = False
Sheets("Data").Activate
Range("A1").FormulaR1C1 = _
"=IF(ISBLANK('S:\SN\SN\2015-S\[2015SNL.xlsx]2015'!RC), _
""-"",'S:\SN\SN\2015-S\[2015SNL.xlsx]2015'!RC)"
Application.ScreenUpdating = True
End Sub
It is also referencing to a specific sheet as you can see the ...2015'!
Any ideas? Thank you in advanced for your assistance
A form not prone to errors is
Dim dirn as String, tabn as String, refs as String
dirn = "S:\SN\SN\2015-S\" ' Change this line
tabn = dirn & "[2015SNL.xlsx]2015"
refs = "'" & tabn &"'!" & "RC"
Dim ws as Worksheet
Set ws = ActiveWorkbook.Sheets("Data")
ws.Range("A1").FormulaR1C1 = "=IF(ISBLANK(" & refs & "),""-""," & refs & ")"
Remember to qualify your Ranges, see this.
To add in variables into a string in VA, you need to close the quotes, and follow with and ampersand: &.
Like so:
Range("A1").FormulaR1C1 = "=IF(ISBLANK('" & Path & "2015'!RC),""-"",'" & Path & "2015'!RC)"
Make sure to add a space between the quotes, the ampersand and the variable name.
I'm at a loss when trying to figure out where this code is tripping up. I am looking to rename the activesheet by using a concat of two ranges on the activesheet and some static text. When only one worksheet is in the workbook, the code works great. As soon as a second worksheet is added, I get a Runtime Error 1004. I'll highlight the line of code where it is breaking. This code currently resides in a normal module.
Option Explicit
Sub updateName()
Dim fNumber
Dim pCheckNumber
Dim asName As String
Dim tempASName As String
Dim worksheetName As Object
If ActiveSheet.Name = "Launch Page" Then Exit Sub
fNumber = ActiveSheet.Range("FlightNumber").Value
pCheckNumber = ActiveSheet.Range("PerformanceCheckNumber").Value
If fNumber <> "" And pCheckNumber <> "" Then
tempASName = "Flight " & fNumber & " | Run " & pCheckNumber & " (0.0%)"
asName = tempASName
MsgBox ActiveSheet.Name & vbCr & asName
ActiveSheet.Name = asName
worksheetName.Caption = asName
Else
Exit Sub
End If
End Sub
I'm in the process of adding error checking to ensure that I don't have duplicate sheet names. However, due to the nature of the field names, this will never occur.
I appreciate all of the insights!
The error you are reporting is, most likely, provoked because of trying to rename a Worksheet by using a name already in use. Here you have a small code to avoid this kind of situations:
Dim newName As String: newName = "sheet1"
Dim addition As String: addition = "_2"
Do While (Not sheetNameFree(newName))
newName = newName & addition
Loop
Where sheetNameFree is defined by:
Function sheetNameFree(curName As String) As Boolean
sheetNameFree = True
For Each Sheet In ActiveWorkbook.Sheets
If (LCase(Sheet.Name) = LCase(curName)) Then
sheetNameFree = False
Exit Function
End If
Next Sheet
End Function
You can adapt this code to your specific needs (for example, by converting addition into a number which grows after each wrong name).
In your code I see one other problem (although it shouldn't be triggering a 1004 error): you are accessing the property Caption from an non-instantiated object (worksheetName), whose exact functionality is not too clear. Just delete this line.
NOTE: good point from KazJaw, you might be using an illegal character. If fNumber and pCheckNumber are numbers or letters, it would be OK.
NOTE2: if with worksheetName you want to refer to an ActiveX Label in your workSheet, better do: ActiveSheet.Label1.Caption (where Label1 is the name of the Label). You cannot define worksheetName as a Label, because it is not a "conventional Label".