I have a Workbook that has a "live" tab, which has around 8 Queries.
Everyday I duplicate this sheet, before refreshing. In the duplicated sheet, I would like to remove all queries, as i dont need them anymore.
I'm trying to create a macro to remove all Queries.
I tried following code, but it doesn't work. error: object doesn't support this method for the line 5.
Sub DelQueries()
Dim q As WorkbookQuery
For Each q In ActiveWorkbook.Queries
If q.Parent.Name = ActiveSheet.Name Then
q.Delete
End If
Next
End Sub
I also tried the code from this question, with some modification, but gets syntax error for line 3.
Sub loop_del_query()
For Each Worksheet In ThisWorkbook.Worksheets
If Worksheet.Name = ActiveSheet.Name
Qcount = Worksheet.Queries.Count
If Qcount > 0 Then
For Each Query In Worksheet.Queries
Query.Delete
Next
End If
End If
Next Worksheet
End Sub
As explained on this post try ;
Option Explicit
Sub DeleteQueries()
Dim wb As Workbook, ws As Worksheet
Dim wq As WorkbookQuery, qname As String
Dim qt As QueryTable, tbl As ListObject
Dim msg As String, dict As Object
Set dict = CreateObject("Scripting.Dictionary")
Set wb = ThisWorkbook
Set ws = wb.Sheets("Sheet1")
' existing queries
For Each wq In wb.Queries
dict.Add wq.Name, 1
Next
' scan table object for query tables
For Each tbl In ws.ListObjects
Set qt = Nothing
On Error Resume Next
Set qt = tbl.QueryTable
On Error GoTo 0
If Not qt Is Nothing Then
qname = qt.WorkbookConnection.Name
If Left(qname, 8) = "Query - " Then
qname = Mid(qname, 9)
'Debug.Print tbl.Name & " Query:" & qname
'delete query if exists
If dict.exists(qname) Then
wb.Queries(qname).Delete
msg = msg & vbCrLf & qname
Else
Debug.Print "Not found", qname
End If
End If
End If
Next
If msg = "" Then
MsgBox "No Queries deleted", vbInformation
Else
MsgBox "Queries deleted:" & msg, vbInformation
End If
End Sub
Related
I have a command button in excel to insert the records to access table. Here's my vba code.
Option Explicit
Sub AddRecordsIntoAccessTable()
Dim accessFile As String
Dim accessTable As String
Dim sht As Worksheet
Dim lastRow As Long
Dim lastColumn As Integer
Dim con As Object
Dim rs As Object
Dim sql As String
Dim i As Long
Dim j As Integer
'Disable the screen flickering.
Application.ScreenUpdating = False
'Specify the file path of the accdb file. You can also use the full path of the file like this:
'AccessFile = "C:\Users\Christos\Desktop\Sample.accdb"
accessFile = ThisWorkbook.Path & "\" & "Database daily activity - Beta 6.accdb"
'Ensure that the Access file exists.
If FileExists(accessFile) = False Then
MsgBox "The Access file doesn't exist!", vbCritical, "Invalid Access file path"
Exit Sub
End If
'Set the name of the table you want to add the data.
accessTable = "DAILY_ACTIVITY"
'Set the worksheet that contains the data.
On Error Resume Next
Set sht = ThisWorkbook.Sheets("Daily Activity")
If Err.Number <> 0 Then
MsgBox "The given worksheet does not exist!", vbExclamation, "Invalid Sheet Name"
Exit Sub
End If
Err.Clear
'Find the last row and last column in the given worksheet.
With sht
lastRow = .Cells(.Rows.Count, "B").End(xlUp).Row
lastColumn = .Cells(1, .Columns.Count).End(xlToLeft).Column
End With
'Check if there are data in the worksheet.
If lastRow < 2 Or lastColumn < 1 Then
MsgBox "There are no data in the given worksheet!", vbCritical, "Empty Data"
Exit Sub
End If
'Create the ADODB connection object.
Set con = CreateObject("ADODB.connection")
'Check if the object was created.
If Err.Number <> 0 Then
MsgBox "The connection was not created!", vbCritical, "Connection Error"
Exit Sub
End If
Err.Clear
'Open the connection.
con.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & accessFile
'Create the SQL statement to retrieve the table data (the entire table).
sql = "SELECT * FROM " & accessTable
'Create the ADODB recordset object.
Set rs = CreateObject("ADODB.Recordset")
'Check if the object was created.
If Err.Number <> 0 Then
Set rs = Nothing
Set con = Nothing
MsgBox "The recordset was not created!", vbCritical, "Recordset Error"
Exit Sub
End If
Err.Clear
'Set the necessary recordset properties.
rs.CursorType = 1 'adOpenKeyset on early binding
rs.LockType = 3 'adLockOptimistic on early binding
'Open the recordset.
rs.Open sql, con
'Add the records from Excel to Access by looping through the rows and columns of the given worksheet.
'Here the headers are in the row 1 and they are identical to the Access table headers.
'This is the reason why, for example, there are no spaces in the headers of the sample worksheet.
For i = 2 To lastRow
rs.AddNew
For j = 1 To lastColumn
'This is how it will look like the first time (i = 2, j = 1):
'rs("FirstName") = "Bob"
rs(sht.Cells(1, j).Value) = sht.Cells(i, j).Value
Next j
rs.Update
Next i
'Close the recordet and the connection.
rs.Close
con.Close
'Release the objects.
Set rs = Nothing
Set con = Nothing
'Re-enable the screen.
Application.ScreenUpdating = True
'Inform the user that the macro was executed successfully.
MsgBox lastRow - 1 & " rows were successfully added into the '" & accessTable & "' table!", vbInformation, "Done"
End Sub
Function FileExists(FilePath As String) As Boolean
'--------------------------------------------------
'Checks if a file exists (using the Dir function).
'--------------------------------------------------
On Error Resume Next
If Len(FilePath) > 0 Then
If Not Dir(FilePath, vbDirectory) = vbNullString Then FileExists = True
End If
On Error GoTo 0
End Function
As an example, I create 2 records in excel. It says that those 2 rows had successfully added into my access table. Yet, the added rows are not found in the access table.
Is there something to do in how I linked the excel and access?
I have a command button in excel to insert the records to access table. Here's my vba code.
Option Explicit
Sub AddRecordsIntoAccessTable()
Dim accessFile As String
Dim accessTable As String
Dim sht As Worksheet
Dim lastRow As Long
Dim lastColumn As Integer
Dim con As Object
Dim rs As Object
Dim sql As String
Dim i As Long
Dim j As Integer
'Disable the screen flickering.
Application.ScreenUpdating = False
'Specify the file path of the accdb file. You can also use the full path of the file like this:
'AccessFile = "C:\Users\Christos\Desktop\Sample.accdb"
accessFile = ThisWorkbook.Path & "\" & "Database daily activity.accdb"
'Ensure that the Access file exists.
If FileExists(accessFile) = False Then
MsgBox "The Access file doesn't exist!", vbCritical, "Invalid Access file path"
Exit Sub
End If
'Set the name of the table you want to add the data.
accessTable = "DAILY_ACTIVITY"
'Set the worksheet that contains the data.
On Error Resume Next
Set sht = ThisWorkbook.Sheets("Daily Activity")
If Err.Number <> 0 Then
MsgBox "The given worksheet does not exist!", vbExclamation, "Invalid Sheet Name"
Exit Sub
End If
Err.Clear
'Find the last row and last column in the given worksheet.
With sht
lastRow = .Cells(.Rows.Count, "B").End(xlUp).Row
lastColumn = .Cells(1, .Columns.Count).End(xlToLeft).Column
End With
'Check if there are data in the worksheet.
If lastRow < 2 Or lastColumn < 1 Then
MsgBox "There are no data in the given worksheet!", vbCritical, "Empty Data"
Exit Sub
End If
'Create the ADODB connection object.
Set con = CreateObject("ADODB.connection")
'Check if the object was created.
If Err.Number <> 0 Then
MsgBox "The connection was not created!", vbCritical, "Connection Error"
Exit Sub
End If
Err.Clear
'Open the connection.
con.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & accessFile
'Create the SQL statement to retrieve the table data (the entire table).
sql = "SELECT * FROM " & accessTable
'Create the ADODB recordset object.
Set rs = CreateObject("ADODB.Recordset")
'Check if the object was created.
If Err.Number <> 0 Then
Set rs = Nothing
Set con = Nothing
MsgBox "The recordset was not created!", vbCritical, "Recordset Error"
Exit Sub
End If
Err.Clear
'Set the necessary recordset properties.
rs.CursorType = 1 'adOpenKeyset on early binding
rs.LockType = 3 'adLockOptimistic on early binding
'Open the recordset.
rs.Open sql, con
'Add the records from Excel to Access by looping through the rows and columns of the given worksheet.
'Here the headers are in the row 1 and they are identical to the Access table headers.
'This is the reason why, for example, there are no spaces in the headers of the sample worksheet.
Application.ScreenUpdating = True
On Error GoTo 0
For i = 2 To lastRow
rs.AddNew
For j = 1 To lastColumn
'This is how it will look like the first time (i = 2, j = 1):
rs(sht.Cells(1, j).Value) = sht.Cells(i, j).Value
Next j
rs.Update
Next i
'Close the recordet and the connection.
rs.Close
con.Close
'Release the objects.
Set rs = Nothing
Set con = Nothing
'Re-enable the screen.
Application.ScreenUpdating = True
'Inform the user that the macro was executed successfully.
MsgBox lastRow - 1 & " rows were successfully added into the '" & accessTable & "' table!", vbInformation, "Done"
End Sub
Function FileExists(FilePath As String) As Boolean
'--------------------------------------------------
'Checks if a file exists (using the Dir function).
'--------------------------------------------------
On Error Resume Next
If Len(FilePath) > 0 Then
If Not Dir(FilePath, vbDirectory) = vbNullString Then FileExists = True
End If
On Error GoTo 0
End Function
This code can only add new records, and it will be error if there is duplicate.
How do I fix the code with the condition:
Update existing access table for the records that is duplicate.
Add the records that is non duplicate
Could do a Find on recordset to determine if data already exists. If it does, focus will be on that record, otherwise pointer will be at recordset EOF.
For i = 2 To lastRow
rs.Find "some field=" & cell reference, , , 1
If rs.EOF Then
rs.AddNew
Else
rs.Edit
End If
For j = 1 To lastColumn
'This is how it will look like the first time (i = 2, j = 1):
rs(sht.Cells(1, j).Value) = sht.Cells(i, j).Value
Next j
rs.Update
Next i
I am trying to resize an Excel table to standard setting of 4 rows and 6 columns
I am able to do for the columns but I still see the empty rows based on the content earlier.
Sub ClearTableContents()
Dim wrksht As Worksheet
Dim objListObj As ListObjects
Dim tableName As String
Dim ActiveTable As ListObject
Dim ActiveRange As Range
Set wrksht = ActiveWorkbook.Worksheets("Sheet1")
Set objListObj = wrksht.ListObjects
With objListObj
For i = 1 To objListObj.Count
tableName = objListObj(i).Name
Set ActiveTable = ActiveSheet.ListObjects(tableName)
'ActiveTable.DataBodyRange.Rows.ClearContents
objListObj(i).DataBodyRange.Rows.ClearContents
On Error Resume Next
'objListObj(i).DataBodyRange.Resize(objListObj(i).DataBodyRange.Rows.Count - 4,
objListObj(i).DataBodyRange.Columns.Count - 6).Rows.Delete
objListObj(i).DataBodyRange.Resize(4, 6).Rows.Delete
If Err.Number <> 0 Then
' process Error
MsgBox "Error: (" & Err.Number & ") " & Err.Description, vbCritical
End If
Next i
End With
End Sub
This will leave the header and three rows so adjust to suit.
Sub x()
With ActiveSheet.ListObjects(1)
.Range.Rows("5:" & .Range.Rows.Count).Delete
.Resize .Range.Resize(4, 6)
End With
End Sub
working on a loop to delete stock info from numerous worksheets in a workbook. Each sheet is named, "Client_ClientFirstName", and each table in each worksheet is the same as the worksheet name. here is the code ive come up with so far, any and all advice is appreciated.
Sub RemoveTickerFromAccounts()
Dim Client As Worksheet
Dim varTickerToFind As String
varTickerToFind = Worksheets("Entry").Cells(5, 1)
Dim tblSearchTable As Range
For Each Client In ActiveWorkbook.Worksheets
If InStr(1, Client.Name, "Client_", vbTextCompare) Then
'ws.Range("B30").Select
Worksheets(Client.Name).Activate
'tblSearchTable = ActiveSheet.ListObjects(1)
ActiveSheet.Range("b30").Select
If Selection.ListObject.Name = Client.Name Then
'tblSearchTable = "Table14"
'tblSearchTable = ActiveSheet.ListObjects(Client.Name).Select
For i = 1 To ActiveSheet.ListObjects(Client.Name).ListRows.Count
If ActiveSheet.ListObject.ListRows(i, 1).Value = varTickerToFind _
Then
tblSearchTable.ListRows(i).Delete
Exit For
Else
MsgBox "Unable to Find Ticker"
Exit For
End If
Next i
End If
End If
Next Client
End Sub
Tested:
Sub RemoveTickerFromAccounts()
Dim Client As Worksheet
Dim varTickerToFind As String
Dim tblSearch As ListObject
Dim bFound As Boolean, i As Long
varTickerToFind = Worksheets("Entry").Cells(5, 1).Value
For Each Client In ActiveWorkbook.Worksheets
If Client.Name Like "Client_*" Then
Set tblSearch = Client.ListObjects(1)
For i = 1 To tblSearch.ListRows.Count
If tblSearch.ListRows(i).Range.Cells(1).Value = varTickerToFind Then
tblSearch.ListRows(i).Delete
bFound = True
Exit For
End If
Next i
If Not bFound Then
MsgBox "Unable to Find Ticker '" & varTickerToFind & "'"
End If
End If
Next Client
End Sub
I am trying to add an Excel sheet named "Temp" at the end of all existing sheets, but this code is not working:
Private Sub CreateSheet()
Dim ws As Worksheet
ws.Name = "Tempo"
Set ws = Sheets.Add(After:=Sheets(Sheets.Count))
End Sub
Can you please let me know why?
Try this:
Private Sub CreateSheet()
Dim ws As Worksheet
Set ws = ThisWorkbook.Sheets.Add(After:= _
ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count))
ws.Name = "Tempo"
End Sub
Or use a With clause to avoid repeatedly calling out your object
Private Sub CreateSheet()
Dim ws As Worksheet
With ThisWorkbook
Set ws = .Sheets.Add(After:=.Sheets(.Sheets.Count))
ws.Name = "Tempo"
End With
End Sub
Above can be further simplified if you don't need to call out on the same worksheet in the rest of the code.
Sub CreateSheet()
With ThisWorkbook
.Sheets.Add(After:=.Sheets(.Sheets.Count)).Name = "Temp"
End With
End Sub
Kindly use this one liner:
Sheets.Add(After:=Sheets(Sheets.Count)).Name = "new_sheet_name"
ThisWorkbook.Sheets.Add After:=Sheets(Sheets.Count)
ActiveSheet.Name = "XYZ"
(when you add a worksheet, anyway it'll be the active sheet)
Try this:
Public Enum iSide
iBefore
iAfter
End Enum
Private Function addSheet(ByRef inWB As Workbook, ByVal inBeforeOrAfter As iSide, ByRef inNamePrefix As String, ByVal inName As String) As Worksheet
On Error GoTo the_dark
Dim wsSheet As Worksheet
Dim bFoundWS As Boolean
bFoundWS = False
If inNamePrefix <> "" Then
Set wsSheet = findWS(inWB, inNamePrefix, bFoundWS)
End If
If inBeforeOrAfter = iAfter Then
If wsSheet Is Nothing Or bFoundWS = False Then
Worksheets.Add(After:=Worksheets(Worksheets.Count)).Name = inName
Else
Worksheets.Add(After:=wsSheet).Name = inName
End If
Else
If wsSheet Is Nothing Or bFoundWS = False Then
Worksheets.Add(Before:=Worksheets(1)).Name = inName
Else
Worksheets.Add(Before:=wsSheet).Name = inName
End If
End If
Set addSheet = findWS(inWB, inName, bFoundWS) ' just to confirm it exists and gets it handle
the_light:
Exit Function
the_dark:
MsgBox "addSheet: " & inName & ": " & Err.Description, vbOKOnly, "unexpected error"
Err.Clear
GoTo the_light
End Function
Try to use:
Worksheets.Add (After:=Worksheets(Worksheets.Count)).Name = "MySheet"
If you want to check whether a sheet with the same name already exists, you can create a function:
Function funcCreateList(argCreateList)
For Each Worksheet In ThisWorkbook.Worksheets
If argCreateList = Worksheet.Name Then
Exit Function ' if found - exit function
End If
Next Worksheet
Worksheets.Add (After:=Worksheets(Worksheets.Count)).Name = argCreateList
End Function
When the function is created, you can call it from your main Sub, e.g.:
Sub main
funcCreateList "MySheet"
Exit Sub
Try switching the order of your code. You must create the worksheet first in order to name it.
Private Sub CreateSheet()
Dim ws As Worksheet
Set ws = Sheets.Add(After:=Sheets(Sheets.Count))
ws.Name = "Tempo"
End Sub
thanks,
This will give you the option to:
Overwrite or Preserve a tab that has the same name.
Place the sheet at End of all tabs or Next to the current tab.
Select your New sheet or the Active one.
Call CreateWorksheet("New", False, False, False)
Sub CreateWorksheet(sheetName, preserveOldSheet, isLastSheet, selectActiveSheet)
activeSheetNumber = Sheets(ActiveSheet.Name).Index
If (Evaluate("ISREF('" & sheetName & "'!A1)")) Then 'Does sheet exist?
If (preserveOldSheet) Then
MsgBox ("Can not create sheet " + sheetName + ". This sheet exist.")
Exit Sub
End If
Application.DisplayAlerts = False
Worksheets(sheetName).Delete
End If
If (isLastSheet) Then
Sheets.Add(After:=Sheets(Sheets.Count)).Name = sheetName 'Place sheet at the end.
Else 'Place sheet after the active sheet.
Sheets.Add(After:=Sheets(activeSheetNumber)).Name = sheetName
End If
If (selectActiveSheet) Then
Sheets(activeSheetNumber).Activate
End If
End Sub
This is a quick and simple add of a named tab to the current worksheet:
Sheets.Add.Name = "Tempo"