I have a userform which is supposed to update different sheets according to combobox "(Select layer to update)" at a time, see attached image, as soon as I press on SAVA DATA button it return error. "Run time error 380" here are my codes. The listbox is supposed to update according the sheet selected under combobox "(Select layer to update)"
.ListBox1.ColumnCount = 28
.ListBox1.ColumnHeads = True
.ListBox1.ColumnWidths = "30,50,40,40,35,43,43,28,25,25,25,25,37,50,45,55,70,60,47,35,35,40,40,40,40,50,160,40"
If iRow > 1 Then
.ListBox1.RowSource = "ActiveSheet!A9:AB" & iRow
Else
.ListBox1.RowSource = "ActiveSheet!A9:AB9"
End If
End With
The RowSource property requires to assign a string reference prefixed by
the actual literal worksheetname plus an exclamation mark (e.g. Sheet1!A9:AB9),
not by characters starting with "ActiveSheet" as presumably there won't be a sheet named
"ActiveSheet".
If you want to use VBA's ActiveSheet property as first part
you could use the following way getting the sheet's address passing the additional
External:=True argument (attention to :=) which returns the fully qualified sheet name as string:
.RowSource = ActiveSheet.Range("A9:AB" & iRow).Address (External:=True)
Another way would be to simply join the string parts via the ampersand connector &,
e.g.
ActiveSheet.Name & "!A9:AB" & iRow (using the name of ANY active sheet) or
ThisWorkbook.Worksheets("Sheet1").Name & "!A9:AB" & iRow (using the tabular sheet name) or
Sheet1.Name & "!A9:AB" & iRow (using the CodeName)
Related
I am trying to create a VBA code that will pull the info to the Left (eventually the right) of a Hyphen based on a range and a cell given by the user.
EX:
Result A & Result B are what I am trying to get too.
I've tested everything in my code until this part and it all works. The entire thing works if I physically type in a cell address (i.e $D2 - I will need the column absolute, but the row relative so that it moves with the range selection). I just can't get it to work with the user input of the "Starting" variable. I need it to be user input because this code will be used on sheets set up completely different than this one. There is a good chance I am missing something obvious but I'm not seeing it #_#. Any suggestions?
**Sorry in advance for the long lines of code
Private Sub Seperate_XtoY_Click()
Dim iCol As Long
Dim iCount As Long
Dim i As Long
Dim Smaller As Range
Dim Bigger As Range
Dim Starting As Range
'Get number of columns that you want to insert with a user input box
iCount = InputBox(Prompt:="How many columns you want to add?")
'Get column NUMBER where you want to insert the new column
iCol = InputBox _
(Prompt:= _
"BEFORE which column do you want to add the new column(s)? (Enter the column number i.e A=1, B=2, C=3, etc)")
'loop to insert new column(s)
For i = 1 To iCount
Columns(iCol).EntireColumn.Insert
Next i
'Makes range variable "Starting" equal to the user input of a range (in this case just 1 cell)
Set Starting = Application.InputBox("Select the FIRST cell of the Original Range of #'s", "Obtain Range Object", Type:=8)
'Makes range variable "Smaller" equal to the user input of a range (where the info will actually populate)
Set Smaller = Application.InputBox("Select a range", "Obtain Range Object", Type:=8)
Smaller.Formula = "=IF(ISNUMBER(SEARCH(""½"", & Starting.Address(0, ""$"") &)),""0.5"",IF(ISNUMBER(SEARCH(""¼"",& Starting.Address(0, ""$"") &)),""0.25"",IF(ISNUMBER(SEARCH(""¾"",& Starting.Address(0, ""$"") &)),""0.75"",LEFT( &Starting.Address(0, ""$"")&, FIND(""–"",& Starting.Address(0, ""$"")&)-1))))"
End Sub
It turns out I had the right idea based on my last comment. I did need remove the variable completely out of the quotes (and then restart them), double check the placing of where I put those quotes, and use a different version of the .Address function to make only my column an absolute reference. All the other lines of code from above were all good, it was just the final line that needed to changed. Thank you #BigBen for giving me a push in the right direction. Looking at the program with fresh eyes also helped lol.
Smaller.Formula = "=IF(ISNUMBER(SEARCH(""½""," & Starting.Address(RowAbsolute:=False) & " )),""0.5"",IF(ISNUMBER(SEARCH(""¼"", " & Starting.Address(RowAbsolute:=False) & ")),""0.25"",IF(ISNUMBER(SEARCH(""¾"", " & Starting.Address(RowAbsolute:=False) & " )),""0.75"",LEFT( " & Starting.Address(RowAbsolute:=False) & " , FIND(""–"", " & Starting.Address(RowAbsolute:=False) & ")-1))))"
I also got the Right side function working too if anyone is interested:
Bigger.Formula = "=IF(ISNUMBER(SEARCH(""– ½""," & Starting.Address(RowAbsolute:=False) & ")),""0.5"",IF(ISNUMBER(SEARCH(""– ¼""," & Starting.Address(RowAbsolute:=False) & ")),""0.25"",IF(ISNUMBER(SEARCH(""– ¾""," & Starting.Address(RowAbsolute:=False) & ")),""0.75"",RIGHT(" & Starting.Address(RowAbsolute:=False) & ",LEN(" & Starting.Address(RowAbsolute:=False) & ")-FIND(""– ""," & Starting.Address(RowAbsolute:=False) & ")-1))))"
PLEASE NOTE for anyone who may want to use a variation of my code I used a slightly bigger hyphen than the typical hyphen ("-" vs "–")
I have a sheet with a list of course names called Matrix. In another sheet named Courses Date I will have the same courses with the date they were taken.
Example:
The course named Safety Driving will be in Matrix on row 1. In Courses Date there is data from E1:BF1 with the same name. If courses need a refreshment there will be another column named exactly the same name of the course + Refresher (Safety Driving Refresher).
What I am trying to do is to find if a course has a refresher or not. My code returns Run-time error '91': Object variable or With block variable not set if nothing is found.
This is my code:
RefresherColNumber = Range("'Courses Date'!E1:BF1").Find(Range("'Matrix'!" & courseColLetter & "1").Value & " Refresher").Column
Add a check
Dim refreshRange As Range
Set refreshRange = Range("'Courses Date'!E1:BF1").Find(Range("'Matrix'!" & courseColLetter & "1").Value & " Refresher")
If Not refreshRange Is Nothing Then RefresherColNumber = refreshRange.Column
You could use Application.Match to test, with IsError, if value found in row and add 4 to where found to get the column. You should qualify your ranges with the parent worksheet object as well to avoid bugs with implicit activesheet referencing.
Dim matchValue As Variant
matchValue = Application.Match(Range("'Matrix'!" & courseColLetter & "1").Value & " Refresher", Range("'Courses Date'!E1:BF1"), 0)
If Not IsError(matchValue) Then RefresherColNumber = matchValue + 4
Good evening. I am desperate for some help with a short piece of VBA Code I am writing.
Public TFOCUS As Integer ' Creates TFOCUS, which is the worksheet in focus
Public RFOCUS As Integer ' Creates RFOCUS, which is the row in focus
Public CFOCUS As String ' Creates CFOCUS, which is the column in focus
Public RECORD As Integer ' Creates RECORD, wich is the row that is having the record written to
FILEPATH.Worksheets(TFOCUS).Range(Cells(RFOCUS, B)).Value = Worksheets(3).Range(Cells(RECORD, A)).Value 'copies focus EmpID to destination
FILEPATH.Worksheets(TFOCUS).Range(Cells(4, CFOCUS)).Value = Worksheets(3).Range(Cells(RECORD, B)).Value 'copies focus Course to destination
FILEPATH.Worksheets(TFOCUS).Range(Cells(RFOCUS, CFOCUS)).Value = Worksheets(3).Range(Cells(RECORD, C)).Value 'copies focus Date to destination
CFOCUS = CFOCUS + 1 'moves focus to next column
RECORD = RECORD + 1 'creates next record
FILEPATH is set to the path of an external Excel workbook. In this instance, TFOCUS is set to 1, RFOCUS is set to 5, CFOCUS is set to "Q", and RECORD is set to 1.
The purpose is to copy records from an external excel document into the active spreadsheet, and reformat them by moving the cell contents about. This will be used to move multiple sources, and will have to deal with every tab in every source document (which could all be named something different).
The issue I am having is that I am recieving a Runtime Error 13: Type Mismatch error when compiling, on the following line:
FILEPATH.Worksheets(TFOCUS).Range(Cells(RFOCUS, B)).Value = Worksheets(3).Range(Cells(RECORD, A)).Value 'copies focus EmpID to destination
I am assuming that this is either to do with the use of TFOCUS as an integer or FILEPATH as a file path. Can anyone suggest:
What exactly the mismatch is
If it is because of using Worksheets(TFOCUS), any way I can reference the worksheet by its number in the tab order using a variable?
Any other suggestions?
Thanks in advance for your help.
You're not showing us where/whether the variables are assigned, but...
Public RFOCUS As Integer ' Creates RFOCUS, which is the row in focus
Public CFOCUS As String ' Creates CFOCUS, which is the column in focus
Try declaring CFOCUS as an Integer. Or better, as a Long, so that your code works beyond row 32767 (the Integer type is 16-bit and signed, so 32768 is an overflowing value).
Also, if FILEPATH is a String, then your code can't work:
FILEPATH is set to the path of an external Excel workbook.
FILEPATH.Worksheets(TFOCUS)
It should be a Workbook object.. but then the identifier you're using is very confusing.
Dim wb As Workbook
Set wb = Workbooks.Open(FILEPATH)
wb.Worksheets(TFOCUS).Range(Cells(RFOCUS, B)).Value = Worksheets(3).Range(Cells(RECORD, A)).Value 'copies focus EmpID to destination
wb.Worksheets(TFOCUS).Range(Cells(4, CFOCUS)).Value = Worksheets(3).Range(Cells(RECORD, B)).Value 'copies focus Course to destination
wb.Worksheets(TFOCUS).Range(Cells(RFOCUS, CFOCUS)).Value = Worksheets(3).Range(Cells(RECORD, C)).Value 'copies focus Date to destination
CFOCUS = CFOCUS + 1 'moves focus to next column
RECORD = RECORD + 1 'creates next record
'save [wb] workbook? Close it?
Set wb = Nothing
May I also suggest to keep YELLCASE for constants, and to use camelCase for locals and PascalCase for everything else?
If RFOCUS is set to "Q" and B and A are integers, then this:
FILEPATH.Worksheets(TFOCUS).Range(Cells(RFOCUS, B)).Value = Worksheets(3).Range(Cells(RECORD, A)).Value
should be:
FILEPATH.Worksheets(TFOCUS).Range(RFOCUS & B).Value = Worksheets(3).Cells(Record, A).Value
Here are all 3 lines:
FILEPATH.Worksheets(TFOCUS).Range(RFOCUS & B).Value = Worksheets(3).Cells(Record, A).Value
FILEPATH.Worksheets(TFOCUS).Cells(4, CFOCUS).Value = Worksheets(3).Cells(Record, B).Value
FILEPATH.Worksheets(TFOCUS).Range(RFOCUS & CFOCUS).Value = Worksheets(3).Cells(Record, C).Value
VBA Insert function VLOOKUP into range,lookup range in other workbook. The file containing the lookup table is achieved using filename_AcctMgr = Application.GetOpenFilename(, , "Select Acct Mgr File", "Select"), then opening the file. Let's call this workbook2.
In workbook1 I am adding the VLOOKUP formula into "F2" and looking up Column "A" values in workbook2, columns A:C. I Then copy the formula to all rows of column "F".
I cannot find the syntax required to properly reference the workbook2 range in columns A:C.
ActiveCell.Formula = _
"=VLOOKUP(activecell.offset(0,-5).address,'ws.name'!A:C,3,FALSE)"
Can anyone suggest the proper syntax?
Try this:
Range("F2").Resize(10).Formula = "=VLOOKUP(A2,[Book2]Sheet1!$A:$C,3,FALSE)"
Or
Range("F2:F10").Formula = "=VLOOKUP(A2,[Book2]Sheet1!$A:$C,3,FALSE)"
EDIT: Sorry I forgot the piece about the filename as a variable:
Dim MyFile As String
Dim vSplit As Variant
Dim iCnt As Integer
MyFile = Application.GetOpenFilename(, , "Select Acct Mgr File", "Select")
vSplit = Split(MyFile, "\")
iCnt = UBound(vSplit)
vSplit(iCnt) = "[" & vSplit(iCnt) & "]"
MyFile = Join(vSplit, "\")
Range("F2:F10").Formula = "=VLOOKUP(A2,'" & MyFile & "Sheet1'!$A:$C,3,FALSE)"
You will need to add error handling in case someone clicks cancel. Also I doubt you want to add the formula to all rows in column f so just define the range you want. My examples is rows 2 to 10.
I am assuming you want the name of the sheet / range to be in a variable, rather than hard-coded. As it it, you have the name of the variable in the middle of your string, but it will be treated as a string, not a variable containing a string.
I suggest that you do something like the following:
Dim sheetName, lookupFrom, myRange ' always declare your variables
sheetName = "This is the sheet name" ' note I added some spaces to make it challenging
lookupFrom = ActiveCell.Offset(0, -5).address
myRange = "'" & sheetName & "'!A:C" ' putting quotes around the string so it's always valid
ActiveCell.Formula = "=VLOOKUP(" & lookupFrom & "," & myRange & ", 3, FALSE)"
You can of course do this all at once - it just gets messy to look at:
ActiveCell.Formula = "=VLOOKUP(" & ActiveCell.Offset(0, -5).Address & ", '" & sheetName & "'!A:C, 3, TRUE)"
Further note - the sheetName can of course contain the name of the other workbook - but you need name of workbook AND sheet... so
sheetName = "[Book2]Sheet1"
would be fine.
In your example you used ws.name (without proper quoting) - but that would not have given you the full path since you need both the workbook and the worksheet name to make sure you reference the right data. Better be explicit - if Excel can make the wrong assumptions about what you want, it will - and you will be left scratching your head...
Since you actually showed you had opened the book, you have the name of the file (the workbook) in your variable filename_AcctMgr. Then you should be able to use:
sheetName = "[" & filename_acctMgr & "]Sheet1"
and take it from there.
I am writing a small score lookup program in VBA and the following code gives the error in the title, i'm new to VBA and the error points to the first line which was generated by Excel itself.
Private Sub btnSearch_Click()
Name = txtSearch.Text
AmountOfEntries = Range("i10")
For i = 1 To AmountOfEntries
If Range("a" + i) = Name Then
cell = i
Else
cell = "Error"
End If
Next i
If cell = "Error" Then
lblScore.Caption = "Your Username is Incorrect. Please Try Again"
Else
lblScore.Caption = "Your Score Is : " + Range("b" + cell)
End If
End Sub
My spreadsheet contains a list of names in the 'A' column then a list of scores in the 'B' column. in 'I10' there is a field containing the amount of entries in the list.
You should try to avoid using "name", "cell" etc (generic terms in VBA) as variable names. Try defining your variables Dim strName as String, i as Integer, intCell as Integer, intAmountOfEntries as Integer.
Also, your range statements should be changed to use & and to specify that you want to use the VALUE not the RANGE aspect of the object:
Range("a" & i).Value and Range("b" & intCell).Value
EDIT =============
Re your comments below:
I think the issue is due to you using cell as an integer (the row number) and also a string ("error"). I would create a new variable to detect if there is an error or not:
Dim blnError as Boolean
Then replace this:
cell = "Error" with blnError = True
Your If statement below will need to be amended to If blnError = True Then
Can you confirm that you have a Sheet called "Sheet1"? If not, then that is why the Sheets("Sheet1") code doesn't work. I normally use the VBA names for sheets instead - in the VBE you can see what they are in the project explorer (name before the brackets) and you can change them using the properties window. Then you just use sheetname.Range("A1").