I'm having issues loading CSV data into the current active workbook, but in a separate sheet.
Right now I'm downloading temporary data into this separate (hidden) sheet, and will refer to it in other sheets. The spreadsheet is approx 4MB, and is updated daily.
How can I get VBScript to load this CSV into a staticly named sheet that would be cleared prior to loading?
URLDownloadToFile 0, fileURL, "%tmp%\tmpExchDBData.csv", 0, 0
Dim dbSheet As Worksheet Dim targetSheet As Worksheet
Workbooks.Open Filename:="%tmp%\tmpExchDBData.csv", _
Format:=2 ' use comma delimiters
Set dbSheet = ActiveSheet
Set targetSheet = Workbooks("Book1").Sheets(3) ' wherever you want to move it to
dbSheet.Move After:=targetSheet ' dbSheet is now in your workbook.
' Hide it. Set dbSheet = ActiveSheet dbSheet.Visible = xlSheetHidden
Importing CSV, especially regularly importing the same CSV file, can be done by defining it as a data source. Select the sheet you want it in, Data Ribbon, From Text.
Once defined you have spectacularly useful options in the connection properties such as "Refresh data when opening" or "Refresh every x minutes".
I've had a similar issue. If it helps, here's the piece of code I ended up with:
Sub Atualizar_B_BR_QSA_IC()
Application.ScreenUpdating = False 'speed up macro execution
Application.EnableEvents = False 'turn off other macros for now
Application.DisplayAlerts = False 'turn off system messages for now
'Atualizar base B_BR_QSA_IC
Dim base_1 As Workbook
Dim plan_1 As Worksheet
Dim nome_arquivo_1 As String
Dim destino_1 As Worksheet
nome_arquivo_1 = Application.ActiveWorkbook.Path & "\BR_QSA_Report_CC.csv"
Set destino_1 = ThisWorkbook.Worksheets("B_BR_QSA_IC")
Set base_1 = Workbooks.Open(Filename:=nome_arquivo_1, Local:=True)
Set plan_1 = base_1.Worksheets(1)
'Limpar a última linha, que é uma linha de totais e não queremos usar
plan_1.Cells(Rows.Count, "A").End(xlUp).EntireRow.Delete
'Caso o excel já não entenda corretamente na abertura, vamos fazer Texto para Colunas do csv
plan_1.Range("A1:A" & plan_1.Cells(Rows.Count, "A").End(xlUp).Row).TextToColumns _
Destination:=Range("A1"), DataType:=xlDelimited, Comma:=True, FieldInfo:=Array(1, 4)
'Agora vamos copiar a base para o arquivo Master (após limpá-lo) e fechar a base sem salvar
destino_1.Range("B2:T" & destino_1.Cells(Rows.Count, "B").End(xlUp).Row).Clear
plan_1.Range("A3:S" & plan_1.Cells(Rows.Count, "A").End(xlUp).Row).Copy
destino_1.Range("B2").PasteSpecial xlPasteValuesAndNumberFormats
base_1.Close savechanges:=False
'Se não há fórmula nas colunas A e B após plugar a base, precisamos colocar até o tamanho da base
If IsEmpty(destino_1.Range("A" & destino_1.Cells(Rows.Count, "B").End(xlUp).Row)) Then
destino_1.Range("A2").Copy Destination:=destino_1.Range("A" & (destino_1.Cells(Rows.Count, "A").End(xlUp).Row + 1) _
& ":" & "A" & destino_1.Cells(Rows.Count, "B").End(xlUp).Row)
'Se já há, precisamos limpar até o tamanho da base
ElseIf Not IsEmpty(destino_1.Range("A" & (destino_1.Cells(Rows.Count, "B").End(xlUp).Row + 1))) Then
destino_1.Rows((destino_1.Cells(Rows.Count, "B").End(xlUp).Row + 1) & ":" & destino_1.Cells(Rows.Count, "A") _
.End(xlUp).Row).EntireRow.Delete
End If
'Maquiagem
destino_1.Cells.Font.Name = "Calibri"
destino_1.Cells.Font.Size = 8
destino_1.Rows.RowHeight = 11.25
Application.DisplayAlerts = True 'turn system alerts back on
Application.EnableEvents = True 'turn other macros back on
Application.ScreenUpdating = True 'refreshes the screen
End Sub
Related
I wrote a code to export data from SAP to an Excel workbook. To do that I open the transaction (IW28 in this case), export the file and save it to a specified location. When the file is opened, I want to copy the data from the exported sheet to my own sheet.
The problem is that the exported sheet won't open while I'm running the macro. When I add a breakpoint in my code, the exported sheet opens when the macro stops. Without this breakpoint the exported sheets only opens after the macro had finished.
'Laden van de data uit transactie IW28 naar de sheet
Dim lastcolumn As Long
Application.DisplayAlerts = False
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
'SAP Variant
SapVariant = "Variant"
'Transaction
Name = IW28
'Current File Location
Map = Application.ActiveWorkbook.Path
If Not IsObject(SapApp) Then
Set SapGuiAuto = GetObject("SAPGUI")
Set SapApp = SapGuiAuto.GetScriptingEngine
End If
If Not IsObject(Connection) Then
Set Connection = SapApp.Children(0)
End If
If Not IsObject(session) Then
Set session = Connection.Children(0)
End If
If IsObject(WScript) Then
WScript.ConnectObject session, "on"
WScript.ConnectObject SapApp, "on"
End If
'Check if file is already open, if so then close the file
If IsOpen(Name & ".xlsx") = True Then Workbooks(Name & ".xlsx").Close
'Open Transaction
session.findById("wnd[0]/tbar[0]/okcd").Text = "/N" & Name
session.findById("wnd[0]").sendVKey 0
'Choose Variant
On Error Resume Next
session.findById("wnd[0]/mbar/menu[2]/menu[0]/menu[0]").Select
session.findById("wnd[1]/usr/txtV-LOW").Text = SapVariant
'Check if variant excists
If Not Err.Number = 0 Then
VarMsgbox = MsgBox("Selecteer variant " & SapVariant & ", dubbelklik om deze te selecteren en klik dan hieronder op ok (niet eerder!)", vbOKCancel, "Selecteer variant")
If VarMsgbox = vbCancel Then Exit Sub
Else
session.findById("wnd[1]/usr/txtENAME-LOW").Text = ""
session.findById("wnd[1]/usr/txtV-LOW").caretPosition = 10
session.findById("wnd[1]").sendVKey 0
session.findById("wnd[1]").sendVKey 8
End If
'Execute Variant
session.findById("wnd[0]").sendVKey 8
'Select all data in SAP
session.findById("wnd[0]/usr/cntlGRID1/shellcont/shell").SelectAll
'Export to Excel
session.findById("wnd[0]/usr/cntlGRID1/shellcont/shell").contextMenu
session.findById("wnd[0]/usr/cntlGRID1/shellcont/shell").selectContextMenuItem "&XXL"
session.findById("wnd[1]/tbar[0]/btn[0]").press
'Add filename and path
session.findById("wnd[1]/usr/ctxtDY_FILENAME").Text = Name & ".xlsx"
session.findById("wnd[1]/usr/ctxtDY_PATH").Text = Map
session.findById("wnd[1]/tbar[0]/btn[11]").press
'Determine lastrow of sheet
Lastrow = Workbooks(Name & ".xlsx").Sheets("Sheet1").Range("B99999").End(xlUp).Row
ThisWorkbook.Sheets(Name).Range("A8:C99999").ClearContents
Workbooks(Name & ".xlsx").Sheets("Sheet1").Range("A2:C" & Lastrow).Copy
ThisWorkbook.Sheets(Name).Range("A8").PasteSpecial xlPasteValues
ThisWorkbook.Sheets("Start").Activate
Application.DisplayAlerts = True
Application.ScreenUpdating = True
You could try the following program construction:
Public Name as String
Sub Makro1()
'Laden van de data uit transactie IW28 naar de sheet
Dim lastcolumn As Long
. . .
session.findById("wnd[1]/tbar[0]/btn[11]").press
call Makro2
End Sub
Sub Makro2()
'Determine lastrow of sheet
Lastrow = Workbooks(Name & .xlsx").Sheets("Sheet1").Range("B99999").End(xlUp).Row
ThisWorkbook.Sheets(Name).Range("A8:C99999").ClearContents
Workbooks(Name & ".xlsx").Sheets("Sheet1").Range("A2:C" & Lastrow).Copy
ThisWorkbook.Sheets(Name).Range("A8").PasteSpecial xlPasteValues
ThisWorkbook.Sheets("Start").Activate
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub
I am opening a specific file set as wb, it is reading the sheet thus my msgbox as a check but when I come to protect the same sheet I get the compiler error.
I have tried numerous methods to complete this task but none work, such as activating the specific sheet "Front Page" selecting it etc but to no avail.
Where am I going wrong?
Thanks
Dim Sht As Worksheet
Dim wb As Workbook
Dim LastRow As Long
Dim WSName As String
Dim URNName As String
Dim lRow As Long
Workbooks.Open Filename:= "\\Folder\1718 list of SD(s) trainees.xlsm"
Worksheets("pivot").Activate
LastRow = 240
For i = 4 To 240
WSName = Cells(i, 6)
URNName = Cells(i, 7)
' Workbooks.Open Filename:="\\Folder\Annex G Usage\" & WSName & " " & URNName & " SD(s)17-18 Statement of Grant Usage.xlsm"
Set wb = Workbooks.Open("\\Folder\Annex G Usage\" & WSName & " " & URNName & " SD(s)17-18 Statement of Grant Usage.xlsm")
MsgBox " Name" & Cells(10, 3)
' wb.Sheets("Front Page").Activate
ActiveSheet.Protect Password:="SOReadyToHelp", _
DrawingObjects:=True, _
Contents:=True, _
Scenarios:=True, _
AllowSorting:=True, _
AllowFiltering:=True, _
AllowUsingPivotTables:=True
ActiveWorkbook.Save
ActiveWindow.Close
Next i
End Sub
In a part of my program, I want to open existing Excel files via VBA in order to modify it and manipulate data.
'Declaration des variables d'objects Excel
Dim wb As Workbook
Dim ws As Worksheet
Dim Fname As String
'Declaration des variables de calcul
Dim a As Double
Dim numimpact, nummatrix, debut, fin, e, n As Long
Dim i As Boolean
'Initialisation des variables
i = True
a = 0
e = 1
numimpact = 1
nummatrix = 1
debut = 2
n = 1000
fin = debut + n
'Boucle de lecture de tous les fichiers Excel
Do While i = True
'Test et incrementation des fichiers Excel
If numimpact < 7 Then
'Ouverture fichiers
Fname = "D:\mmLaurencon\Desktop\NL\Test\CFRP1\"
Set wb = Workbooks.Open(Fname & "CFRP1-" & nummatrix & "-" & numimpact & ".xlsm")
'Set wb = Workbooks.Open("D:\mmLaurencon\Desktop\NL\Test\CFRP 1\CFRP1-1-" & numimpact)
Set ws = wb.Worksheets(1)
'Parcourir colonne B
Do While Cells(e, 2).Value <> ""
For Each e In Columns(2)
Cells(fin, 3).Value = Application.Sum(Cells(debut, 2).Value, Cells(fin, 2).Value) / n
debut = debut + 1
fin = fin + 1
e = e + 1
'save the file
ActiveWorkbook.SaveAs Filename:= _
"D:\mmLaurencon\Desktop\NL\Test\CFRP " & nummatrix & "\CFRP1-1-" & numimpact & ".xlsm", _
FileFormat:=xlOpenXMLWorkbookMacroEnabled, CreateBackup:=False
'close the file
wb.Close
Next
numimpact = numimpact + 1
Loop
ElseIf numimpact = 7 Then
nummatrix = nummatrix + 1
numimpact = 1
ElseIf nummatrix = 10 Then
i = False
End If
Loop
I made this code, but a runtime error 1004 File could not be found appears on line Set wb = Workbooks.Open (Fname & "CFRP1-" & nummatrix & "-" & numimpact & ".xlsm"). I don't understand why as I indicated the right path and file. I tried another way of doing this Set wb = Workbooks.Open("D:\mmLaurencon\Desktop\NL\Test\CFRP 1\CFRP1-1-" & numimpact) but a new runtime error 1004 the document may be read-only or encrypted appears.
Have you an idea about what is going wrong? Thank you in advance!
This line Set wb = Workbooks.Open(Fname & "CFRP1-" & nummatrix & "-" & numimpact & ".xlsm") is trying to open file D:\mmLaurencon\Desktop\NL\Test\CFRP1\CFRP1-1-1.xlsm and is entirely different to your second attempt Set wb = Workbooks.Open("D:\mmLaurencon\Desktop\NL\Test\CFRP 1\CFRP1-1-" & numimpact).
The second attempt is missing the file extension, and the file path is different. The file path differs at this point D:\mmLaurencon\Desktop\NL\Test\CFRP1 compared to D:\mmLaurencon\Desktop\NL\Test\CFRP 1
I assume that both attempts were supposed to open the same file? You will need to correct the file paths - I'm not sure which is the correct one.
I am trying to delete empty rows in every sheet using this code in Excel 2010:
Private Sub CommandButton1_Click()
Dim I As Integer
'For all sheets...
For I = 1 To Sheets.Count
'select corresponding sheet
Sheets(I).Select
Sheets(I).Activate
'write delete code
For fila = 1 To 10
If Cells(fila, 4).Value = "" Then
Rows(fila).Delete
End If
Next fila
'Go to next sheet
Next
End Sub
This code only deletes rows on my first active sheet.
Always remember to loop backward when deleting objects (in your case rows), so use For i = 10 to 1 Step -1.
Also, try to avoid using Select and Activate, instead you could directly reference the Worksheet or Range. In this case use directly the ws defined as Worksheet, to see if If ws.Cells(fila, 4).Value = ""
Code
Option Explicit
Private Sub CommandButton1_Click()
Dim I As Integer, fila As Long
Dim ws As Worksheet
' loop through all worksheets
For Each ws In ThisWorkbook.Worksheets
' loop backwards when deleting objects
For fila = 10 To 1 Step -1
If ws.Cells(fila, 4).Value = "" Then ws.Rows(fila).Delete
Next fila
Next ws
End Sub
Maybe this solution will help you :
It will clean all worksheets in your workbook and delete empty rows.
In the end, msg box will tell you the percentage of rows that were deleted for each sheet.
Best regards,
Sub Clean()
Dim Sht As Worksheet, DCell As Range, Calc As Long, Rien As String, Avant As Double, plage As Range
On Error Resume Next
Calc = Application.Calculation ' ---- mémorisation de l'état de
recalcul
'------------------------------------------------------------
MsgBox "Pour le classeur actif : " _
& Chr(10) & ActiveWorkbook.FullName _
& Chr(10) & "dans chaque feuille de calcul" _
& Chr(10) & "recherche la zone contenant des données," _
& Chr(10) & "réinitialise la dernière cellule utilisée" _
& Chr(10) & "et optimise la taille du fichier Excel", _
vbInformation, _
"d'après LL par GeeDee#m6net.fr"
'-------------------------------------------------------------
MsgBox "Taille initiale de ce classeur en octets" _
& Chr(10) & FileLen(ActiveWorkbook.FullName), _
vbInformation, ActiveWorkbook.FullName
'------------------------------------------------------------
With Application
.Calculation = xlCalculationManual
.StatusBar = "Nettoyage en cours..."
.EnableCancelKey = xlErrorHandler
.ScreenUpdating = True
End With
'-------------------- le traitement
For Each Sht In Worksheets
Avant = Sht.UsedRange.Cells.Count
Application.StatusBar = Sht.Name & "-" & Sht.UsedRange.Address
'-------------------Traitement de la zone trouvée
If Sht.UsedRange.Address <> "$A$1" Or Not IsEmpty(Sht.[A1]) Then
Set DCell = Sht.Cells.Find("*", , , , xlByRows, xlPrevious)(2)
'----------------Suppression des lignes inutilisées
If Not DCell Is Nothing Then
Sht.Range(DCell, Sht.Cells([A:A].Count, 1)).EntireRow.Delete
Set DCell = Nothing
Set DCell = Sht.Cells.Find("*", , , , xlByColumns, xlPrevious)(, 2)
'----------------Suppression des colonnes inutilisées
If Not DCell Is Nothing Then Sht.Range(DCell, Sht.[IV1]).EntireColumn.Delete
End If
Rien = Sht.UsedRange.Address
End If
ActiveWorkbook.Save
'---------------------Message pour la feuille traitée
MsgBox "Nom de la feuille de calcul :" _
& Chr(10) & Sht.Name _
& Chr(10) & Format(Sht.UsedRange.Cells.Count / Avant, "0.00%") & " de la taille initiale", _
vbInformation, ActiveWorkbook.FullName
Next Sht
'--------------------Message fin de traitement
MsgBox "Taille optimisée de ce classeur en octets " & Chr(10) & FileLen(ActiveWorkbook.FullName), _
vbInformation, _
ActiveWorkbook.FullNameActive
'--------------------
Application.StatusBar = False
Application.Calculation = Calc
End Sub
I import from Access to Excel a data (tables) file, but I don't manage to remove the filter. I get a 1004 error (Delete of Range is failed). I also can't remove it by hand.
Sub Openaccessdatafile()
'Niet blad updaten
Application.ScreenUpdating = False
Sheets.Add.Name = "Gegevens alginaten"
Set sh = ThisWorkbook.Sheets("Gegevens alginaten")
LR = sh.Cells(Rows.Count, "A").End(xlUp).Row
Filename = Application.GetOpenFilename("Excel files (*.xls*), *.xls*")
MsgBox Filename
If Filename <> False Then
Workbooks.Open (Filename)
ActiveSheet.UsedRange.Copy sh.Range("A" & LR)
ActiveWorkbook.Close
Sheets("Start").Cells(2, 5).Value = "Ok"
Else
MsgBox "Geen bestand aangeklikt."
Application.DisplayAlerts = False
Sheets("Gegevens alginaten").Delete
Application.DisplayAlerts = True
End If
'Wel blad updaten
Application.ScreenUpdating = True
Sheets("Start").Select
End Sub
Apparently exporting it with Access through a VBA macro button does work better. Than I could remove the row, because the filter is than not added in the exported file.