I´m trying to create a macro that can change the name of a table without having to indicate the table or the sheet names.
The only way to change the name of a table I found was:
ActiveSheet.ListObjects("Table1").Name = "newnametable"
The way I found it best to solve this is by the "Send Keys" function, I tried to indicate with VBA to follow the commands ALT+J+T+A and rename the currently selected table by the following code:
Sub NewTableName()
Application.SendKeys ("%jta")
Application.SendKeys ("TableNewName{Enter}")
End Sub
This works only when I put a button in front of the table and run it from there
The problem comes when I want to run the code from the VBA excel application. When I execute the macro this way, the send keys are played inside the VBA app, not inside the excel sheet I need.
Try to avoid sendkeys as all cost. Esspecially when you're working inside a workbook. There are ways to reference every object or range or whatever inside a workbook.
I assume you're trying to reference the table by selecting a cell within the table then running your macro.
Here is the code I use:
Option Explicit
Sub RenameThisTable()
Dim Tbl As ListObject
Set Tbl = Selection.ListObject
If Not Tbl Is Nothing Then
Tbl.Name = "NewName"
End If
End Sub
If I select a cell inside table2:
and run the macro, the table name changes from "Table2" to "NewName"
I've been wracking my brain trying to solve this issue, and I bet it's super simple, but the answer is eluding me!
I'm trying to add a new row to a filtered table in Excel via a macro button. The macro works when the table is unfiltered but, due to client requirements, they want to add rows regardless of how filtered the table is. The user uses the column header dropdowns to filter the table - sometimes three or filters applied at a time.
Here is the current VBA code I'm using;
Public Sub Add_new_row_2()
Dim tbl As ListObject
Dim rw As Range
Set tbl = Sheets("Master Input").ListObjects(1)
Set rw = tbl.ListRows.Add.Range
Sheets("Data").Range("CF2:KX2").Copy rw
End Sub
The code copies a fully formatted blank row within a range (CF2:KX2) located on a separate tab and pastes the row to the bottom of the table. It works well whilst the table is unfiltered or sorted, but when the user tries to apply multiple column filters, they get a Runtime error "1004".
Is there a way to add a new row despite any heavy filtering?
I got stuck at a problem with Excel VBA.
I am supposed to do the kinda easy task of copy/paste a variable range of cells from "sheet2" into the same range in "sheet1".
500 Rows like in my code is far too much, but I tried it this way, to "catch" the variable aspect.
The tricky part is, that the range in "sheet1" is a table(which gets created from TFS).
Sub CopyP()
Sheets("Sheet1").Range("B3:F500").Value = Sheets("Sheet2").Range("B3:F500").Value
SheetObject.ListObjects (ListObjectName)
Range("NAME OF TABLE[Iteration Path]").SpecialCells(xlCellTypeBlanks).EntireRow.Delete
End Sub
The [Iteration Path] is a column name of my table, i want to check in this column/with this parameter, if the "row" is empty.
I know the code is far from being good or clean but the table is giving me a hard time copying.
With this code I got another problem: the table gets created from TFS, no problem to copy into that, BUT the name of the table is variable(seems like TFS creates the name), so unless I put the name manually in the code, the "program" cant execute, because of missing range.
Didn't find a way to get a return of the table name somehow.
But I think I am just following the wrong path overall, maybe someone can be bring me on the right track.
My other Idea is to Iterate through the Rows in Sheet 2 to fetch just as much data is needed and then copy them with an iteration into the table. But i guess I would be the same problem with the table-name there.
Every information I find using google , talks about tables where the user can "name" the table. In my case I cant, so I have to work with the name TFS uses for my table.
Further to my comments below your question, I just typed this in notepad. Please amend it to suit your need.
This will give you the names of all tables in the activesheet. If there are multiple tables then you will get multiple names. (UNTESTED AS POSTING FROM PHONE)
Sub sample()
Dim objLB As ListObject, TableName As String
For Each objLB In ActiveSheet.ListObjects
TableName = objLB.Name
Exit For
Next
Range(TableName & "[Iteration Path]").SpecialCells(xlCellTypeBlanks).EntireRow.Delete
End Sub
I have the following code in excel VBA
'Create query table to hold the rates.
With objBK.Worksheets(1)
Set objQT = .QueryTables.Add( _
Connection:="URL;https://xxx.output=XLS", _
Destination:=.Range("A1"))
End With
https://xxx.output=XLS return an XLS table that is written in A1 cell of my worksheet.
The problem is that every time I run this query it keeps adding the table in A1 shifting the previous table and NOT overriding it.
How can I override old table?
You keep adding new ones when you actually want to adjust the existing one. Give your QueryTable a name (objQT.Name = "blah"). Then when you need to adjust it, get hold of that QueryTable and make your adjustments to it.
Alternatively, just delete the old one before creating a new one.
I've got an Access 2007 database on which I have created around 15 SQL queries to process specific data, I have created a main frame navigation menu using menus in Access, I now need to extract all th queries to Excel using VBA code, I have managed to do this with the code below by creating a button and specifying this code to it.
Private Sub query1_Click()
DoCmd.TransferSpreadsheet acExport, _
acSpreadsheetTypeExcel9, "Total Users and Sessions", _
"C:\UsersandSessions.xls", , "Total Users & Sessions"
End Sub
Now my problem at the moment is that fine the query is exported to Excel, but it is done so without any formatting applied at all, I would like to add some formatting at least to the headers and maybe a title inside the spreadsheet, and one thing I dont really like is that all records are being started from the first cell. Also I would prefer that if I hit that button again in Access and the Excel spreadsheet has already exists with that query output then when clicked again it will write again to a the next available sheet.
Any suggestions or ideas a very welcome.
The short story, is you can't. You might be able to do some scripting on the Excel side to format the resulting file. If you want something pretty, you probably want to create a report.
You could, instead mount the excel sheet as a table, and then on a separated sheet in the excel file, reference the first sheet, and format the second sheet for viewing.
if you use DoCmd.TransferSpreadsheet and create an original and then edit it so that the formatting is correct, you can then run DoCmd.TransferSpreadsheet again and it will update the file with the values but keep the formatting.
However, if a human then changes the file by adding new tabs, or adding calculations, etc, then the DoCmd.TransferSpreadsheet will no longer work and will fail with an ugly error message. So what we do in our enviroment is DoCmd.TransferSpreadsheet to an original file with formatting, and follow that up in the VBA by copying the file to the users desktop, and then opening that copy so the user doesn't mess up the original source excel file.
This approach is a minimum code, clean, and easy to maintain solution. But it does require a extra "source" or original file to be hanging around. Works in Access 2007.
You also would like the results to end up on a new tab. Unfortunately, I think it will take some excel automation to do that. The VBA inside Acccess can call a function inside the VBA in Excel. That VBA could then copy the tabs as needed.
My idea would be a hybrid of Excel automation from Access and creating a template in Excel as well that would have a data table linked to your query.
To start create your data table in Excel. You can start three rows down and two columns to the right if you want or wherever. Go to your data tab and click access, find your db, choose your query you want to link to, choose table as the radio button but click properties next instead of ok, uncheck the enable background refresh, this part is critical ... under the definition tab in the connection string you will see a part that says Mode=Share Deny Write change that to Mode=Read, this will make sure that the query refreshes without errors from an MS Access VBA while the db is open and will keep your users from writing back to the db in case your query is a writeable query. Once you set that up you can adjust the table formatting however you choose from the table design tab and it will keep that formatting.
For the purposes of this we are going to assume you started the table in cell B4 ,and your named the worksheet CurrentDay, for purpose of the following VBA example be sure to replace that reference with your actual placement.
Next go back to Access and write your VBA first ensure that in your VBA window you have the reference to Microsoft Excel 12.0 Object Library is selected by going to Tools > References and selecting it from the alphabetical listing.
Create your sub as follows:
Sub query1_click()
Dim xl as Excel.Application
Dim wbk as Excel.Workbook
Dim wks as Excel.Worksheet
Dim RC as Integer
Dim CC as Integer
Set xl = New Excel.Application
Set wbk = xl.wbk.Open "X:\Filelocation\FileName.xlsx" 'name and path you saved the file you previously created
xl.Visible = True
'The above is not necessary but you may want to see your process work the first few times and it will be easier than going to task manager to end Excel if something fails.
RC = xl.Application.CountA(xl.wbk.Worksheets("CurrentDay").Range("B:B")) + 3 'This will count the rows of data in your table including your header so you can copy the data to another tab dynamically as the size of your table expands and shrinks we add 3 to it because we started at row 4 and we need the location of the last row of the record set.
CC = xl.Application.CountA(xl.wbk.Worksheets("CurrentDay").Range("4:4")) + 1 'This counts the header row and adds one space because we will use this as a location holder for our copy / paste function
Set wks = xl.wbk.Worksheets.Add
wks.Name = format(date(),"MM_dd_yy") 'this will name the tab with today's date... you can eliminate this step if you just want the sheets to be the generic Sheet1, Sheet2, etc.
With xl.wbk
.Worksheets("CurrentDay").Range(Cells(4,2),Cells(RC,CC)).Copy
.wks.PasteSpecial xlPasteValues 'This pastes the values so that the table links do not paste otherwise every tab would just refresh everyday.
.wks.PasteSpecial xlPasteFormats 'This gets your formatting.
.RefreshAll 'This will refresh your table
Wend
With xl
.Save
.Close False
.Quit
Wend
Set xl = Nothing
Set wbk = Nothing
Set wks = Nothing
End Sub
That should get you to have your data to not start on A1 of your sheets, save your old data each time, and automate the steps from access.