Quantcast
Channel: Active questions tagged excel - Stack Overflow
Viewing all 89226 articles
Browse latest View live

Run-time error '-2147352571(80020005) Type mismatch

$
0
0

I have Run-time error '-2147352571(80020005) Type mismatch in line .AddItem rs(1):

Private Sub UserForm_Activate()
    If dbconn.State = adStateClosed Then dbconn.Open strConn

    Dim rs As New ADODB.Recordset

    ListBox1.Clear
    ListBox1.ColumnCount = 6
    rs.Open "select idClient,client_name,Address,City,state,country from  tblClients ", dbconn

    Do While rs.EOF = False
        i = i + 1
        With UserForm2.ListBox1
            .AddItem rs(1) '---------> getting ERROR HERE PLEASE LET ME KNOW
            .List(.ListCount - 1, 1) = rs(2)
            .List(.ListCount - 1, 2) = rs(3)
            .List(.ListCount - 1, 3) = rs(4)
            .List(.ListCount - 1, 4) = rs(5)
            .List(.ListCount - 1, 5) = rs(0)
        End With
        rs.MoveNext
    Loop
    rs.Close

    With cmbCountry
        .AddItem "United States"
        .AddItem "Canada"
        .AddItem "Germany"
        .AddItem "Australia"
    End With
    cmbCountry.ListIndex = 0
End Sub

Find and replace every second occurrence of a word in a column macro

$
0
0

I want to change every second occurrence of a word in a column to a different word example:

Column A    Column B      
Blank        123
Blank        124
XXXXX        125
Blank        126
Blank        127
XXXX         128
XXXX         129
XXXX         130
etc
Blank        150
Blank        151

I want to change every second 'Blank' to something else e.g. 'Blank1' The number of rows varies up to ~ 300. There may be up to about 30 occurrences of the 2 'Blank' pairs. The XXXX are other labels Want end result to be:

Column A    Column B      
    Blank        123
    Blank1        124
    XXXXX        125
    Blank        126
    Blank1        127
    XXXX         128
    XXXX         129
    XXXX         130
    etc
    Blank        150
    Blank1        151`

R script for turning a 3-dimensional .nc file into excel spreadsheet(s?)

$
0
0

I am in desperate need of help. I’m a PhD candidate and unfortunately, the university has essentially closed for the holidays so there aren’t people around to ask for help.

So I usually work in physiology, but I’m currently working with ecological data, and this is where I’ve become stuck (I’ve been stuck here for over a week). The file I need to read is a ‘.nc’ file which, as far as I can tell, it has 3 dimensions (Latitude, Longitude, and Time[date]) with 7(?) variables.

Excel can’t read it even with the NetCDF4 plug-in. So, I’ve tried putting it into Rstudio and it CAN read it, but just can’t display it to me in any sort of readable manner.

Even when I try and display some variables, nothing comes out in a readable manner.

The data is publically accessible from https://portal.aodn.org.au, and are readings of Alkalinity-Carbon-Salinity-Temperature of the Indian ocean surrounding Western Australia (lat and long co-ordinates) from years 1900 – 2013.

My end goal is to turn this data into a readable excel file so I can begin to analyse it. Any help would be greatly appreciated.

How to connect filename with the cell value in Excel and paste it formatted into Word

$
0
0

I have an Excel file with a table where each row represents address and description of property; as well .jpg files - photos of buildings. Each .jpg filename starts with the number (for example 66_foto1.jpg) and the same number contains column "OBJECTID" in the table.

I would like to connect ID value from Excel table with the name of photo and to paste it into Word file. For now I have the code which allows me to paste different photos having the same ID one by one (for example 66_foto1.jpg, 66_foto2.jpg, 66_foto3.jpg):

    Dim fso As Object
    Dim objfolder As Object
    Dim objfile As Object
    Dim lCount As Long
    Dim strpath As String
    Dim objsub As Object

    strpath = "C:\Users\xxx\"
    Set fso = CreateObject("Scripting.FileSystemObject")
    Set objfolder = fso.GetFolder(strpath)

    For Each objfile In objfolder.Files
        If UCase(objfile.Name) Like "66_*" Then lCount = lCount + 1
    Next objfile

but I still need to convert 66_*.jpg into variable and create a loop.

Excel Table

Querying future dates when date is stored as a string

$
0
0

Date is stored as a string.

Date Example: 11012019

I need to query where dates are entered incorrectly as a future date, but I can't do that if it's being stored as a string.

Goal: Query future dates greater than today

Search multiple worksheets for a user given keyword, return the row results of all instances

$
0
0

I am trying to search multiple worksheets for a keyword. If the keyword is found in the worksheet, I would like to return the row results in a listbox.

Here is what I am trying:

Dim wb as ThisWorkbook
Dim ws as Worksheet
Dim keyword as variant

keyword = ItemSearchForm.KeywordTextBox.Value

For each ws in ThisWorkbook
       If keyword = 'any value in the cells below the column headings' Then
       Populate a listbox with these row results
       Else
       MsgBox ("Please insert a valid keyword")
       End if

Next

Is this the right idea? And if so, how can I fix it?

The user selects a criteria (maybe title of a book or a certain year something was made) on the ItemSearchForm, then a textbox appears asking for a keyword (could be a string for a name or a integer for a year or IDNumber), then a listbox appears with the results, all in the same form.

Uploading Records from Excel file to Server - Desktop App

$
0
0

I have requirements as below :

There is a folder named BATCH inside D:// drive of my PC.

Now this D://BATCH contains excel files with any random names. Every excel file has only one record.

I have to create .exe file or any Desktop Application which lets the user to browse the BATCH folder and then can upload the content or data from the excel files to our Server. We have to put the excel data into JSON and then have to upload it to the server.

One more thing is that If I have uploaded data from 3 files and then again user tries to upload by selecting the folder, data which are new or not uploaded only those data should be upload. The data in BATCH folder is generating daily with connected machine.

My background is for Web and Mobile development. So, little bit confused of achieving this thing as explained above.

So, How can I achieve this? Which technology I have to use or which are the tools that can be useful?

Thanks for the support.

Simplifying gross excel formula

$
0
0

I'm trying to sum a range of values from an external workbook. The range changes depending on values in the current workbook.

The way I am currently doing it is with this formula:

SUM(INDIRECT(CONCATENATE("'[EXTERNALBOOK.xlsm]Actual'!", ADDRESS(MATCH(F3+1, '[EXTERNALBOOK.xlsm]Actual'!$B$1:$B$378,0), 88), ":", ADDRESS(MATCH(G3, '[EXTERNALBOOK.xlsm]Actual'!$B$1:$B$378,0), 88))))

It's very hard to parse and I'm sure it can be greatly simplified. I would be very surprised if this is the 'normal' way to sum an external range.

How it works:

  1. First construct the address where the sought values are found. They specifically are dates. ie. we might want the values from then 2nd of November to the 15th, so we build strings representing these cells (eg. $A$37 and $A$50).

  2. Concatenate these addresses with the name of the worksheet to produce a valid range ie. output is '[EXTERNALBOOK.xlsm]Actual'!$A$37:$A$50

  3. Use INDIRECT to convert this back from a string to something we can actually pass to SUM

  4. call SUM(*string_built_above*)

Conceptually this isn't that hard to follow, but it's hard to tell that this is what's happening when you look at that big long unformatted excel formula. Is there a way to simplify this? Am I missing an obvious solution/going the super long way about this?

I appreciate any and all help!


Checkedlistbox in excel ribbon

$
0
0

I have created an Excel ribbon. It contains a drop down in which the name of all the sheets in the workbook are populated when you open the workbook. Now I want to select more than one sheet from the drop down list and do some operation on those sheets only. Is there any way to select multiple choices from drop down list.In Ribbon Control Checkedlistbox control is not available for Excel ribbon. This was the only way I knew to handle this scenario. Any help would be great.

Storage of Range Values after .Find

$
0
0

Greeting everyone, this is part of a bigger code that both filters based on input text and then creates subtotals out of the values associated with warranty subtypes, this is applied to several different sheets and it all works wonders.

Since there's the possibility of MANY different Warranties subtypes being present, I proceed to check for each one individually, first for an exact match case for "WarrantyPrefA Total" (this should be on the AJ Column) if it exists, I want it to store that range value inside a variable(GaRangeID), so that I can apply an offset of that range to grab the 2 numerical values present in other columns and paste it on another Workbook. If it Doesn't exist, I want it to terminate that find, and proceed to find another exact match case. But its not working. My guess is i'm messing up the .find inner syntax to search in the incorrect range.

Dim GaRangeID As Range
Dim WBModeloA1 As Worksheet
Dim WBModeloA2 As Worksheet
Set WBModeloA1 = Workbooks("ModeloAnalisis.xlsm").Sheets("Cartera 1")
Set WBModeloA2 = Workbooks("ModeloAnalisis.xlsm").Sheets("Cartera 3")

'GPB

 Dim strSearch As String
    Dim lastrow As Long

    strSearch = "WarrantyPrefA Total"
    lastrow = WBevoDeuM.Range("AJ"& Rows.Count).End(xlUp).Row

   Set GaRangeID = WBevoDeuM.Range("AJ1", "AJ"& lastrow).Find(What:=strSearch, LookIn:=xlFormulas, LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:= _
        xlNext, MatchCase:=False, SearchFormat:=False)

    If Not GaRangeID Is Nothing Then

       WBModeloA1.Range("E67") = GaRangeID.Offset(0, -3).Range("A1")
       WBModeloA1.Range("E67").Value = WBModeloA1.Range("E67").Value / 1000


       WBModeloA2.Range("H91") = GaRangeID.Offset(0, -21).Range("A1")
       WBModeloA2.Range("H91").Value = WBModeloA2.Range("H91").Value / 1000

    Else
    End If

'GPA

   Set GaRangeID = Cells.Find(What:="WarrantyPrefB Total", After:=ActiveCell, LookIn _
   :=xlFormulas, LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:= _
        xlNext, MatchCase:=False, SearchFormat:=False)

If Not GaRangeID Is Nothing Then

   WBModeloA1.Range("E65") = GaRangeID.Offset(0, -3).Range("A1")
   WBModeloA1.Range("E65").Value = WBModeloA1.Range("E65").Value / 1000

   WBModeloA2.Range("H90") = GaRangeID.Offset(0, -21).Range("A1")
   WBModeloA2.Range("H90").Value = WBModeloA2.Range("H90").Value / 1000

Else
End If

'the reason I show it repeats the same structure but with another find afterwards i'ts because I used to have the "find" part defined in another way.

The following way it properly pastes the subtotals onto the other workbook, but I discarded it since it always sets the GaRangeID as the active cell, when the search gets nothing, the active cell remains as the old subtotal found, and so it just pastes the values of WarrantyA onto B.

Cells.Find(What:="WarrantyPrefB Total", After:=ActiveCell, LookIn _
    :=xlFormulas, LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:= _
    xlNext, MatchCase:=False, SearchFormat:=False).Activate
    Set GaRangeID = ActiveCell

'If you could help me fix either one, or if you have a more elegant solution, I'll owe you one :)

Removing double quotes- Excel to Notepad

$
0
0

I have written a macro to dump excel cells on to a notepad file. The cell contents appear along with a " in the .txt file. How do I get rid of the double quotes before writing it to the file?

Sub makeFile1()

    Dim ce As Range
    Dim ws As Worksheet

    Open "C:\queries.txt" For Output As #1
    For Each ws In ActiveWorkbook.Worksheets
          Write #1, "Create Table "& ws.Name
            For Each ce In Range("G2:G10")
               If ce.Next = "" Then
               Write #1, ce.Value
               ElseIf ce.Value <> "" Then
               Write #1, ce.Value & ","
               End If

            Next ce
    Next ws
    Close #1

End Sub

Is there a PIA for Office365 and Visual Studio 2010?

$
0
0

Is there a PIA for Office365 and Visual Studio 2010? If so how do I get it? If not then what is the equivalent? There are no PIAs on my PC for Office365 or anything beyond Office 14. Context: I am migrating all my files/Folders from an old PC to a new PC. The systems involved have the following installed: Old: Windows 7(64 bit), Office 2007, Visual Studio 2010 Professional New: Windows 10 (64 bit), Office365, Visual Studio 2010 Professional

Much of my work involves Excel VBA routines calling COM enabled Class Libraries (.dll) to obtain and manipulate various data which the .dlls then return the results to Excel for display and/or other manipulations. The Class Libraries are written by me using VS2010 VB.Net. All of this works as expected on my old PC.

The first sign of my Problem is this Warning: C:\Windows\Microsoft.NET\Framework\v4.0.30319\Microsoft.Common.targets(2015,5): warning MSB3304: Could not determine the dependencies of the COM reference "Microsoft.Office.Interop.Excel". Element not found. (Exception from HRESULT: 0x8002802B (TYPE_E_ELEMENTNOTFOUND)) which I get when attempting to rebuild a Class Library assembly with Visual Studio 2010.

Since this was a Warning, I pushed on in Debug mode. My Startup Project is a test application which starts Excel with a test Workbook. In that Workbook, I have code that attempts to set up an instance of my .dll, the .dll that Imports Microsoft.Office.Interop.Excel. It errors out with the message: Error trying to Create the StockDataTest.Tester instance. Error is: runtime error '429: ActiveX component can't create object'.

I suspect that the runtime error is related to the build time Warning and have been searching and poking around based on that suspicion. I suspect that it has to do no PIA for Office365/VS2010. The first time I opened this Solution after copying to the new machine, VS210 changed the old reference to "Microsoft.Office.Interop.Excel". to a reference that actual refers to C:\Windows\assembly\GAC_MSIL\Microsoft.Office.Interop.Excel\15.0.0.0__71e9bce111e9429c\Microsoft.Office.Interop.Excel.dll which is the one that it could not determine the dependencies for.

Any help will be appreciated.

VBA Reduce run time using other functions

$
0
0

I have this original code of mine that loops through one folder and files inside the folder to copy and paste data out into a new worksheet using .find and then i trim the data using .find,split,Right,Left function to remove any unwanted extra letters so that it would look neater , and if a certain string wasn't found, i will have to search for another string again to make sure all columns are filled with data. However too many .find makes the runtime extremely long. I have provided the code below after my original coding, please take a look and let me know how can i implement it and reduce runtime, other suggestions are welcomed too!

Some of the strings that i search using .find may seem like an typo, please don't mind it, its just an example.

Option Explicit

Sub GenerateData()

    Application.ScreenUpdating = False

    Dim wks As Worksheet
    Dim wkb As Workbook
    Set wkb = ActiveWorkbook
    Set wks = wkb.Worksheets.Add(After:=wkb.Worksheets(wkb.Worksheets.Count), Type:=xlWorksheet)

    ' Add headers data
    With wks
        .Range("A1:K1") = Array("Test", "Temp", "Type", "Start", "FileName", "No", "End", _
        "Month", "Smart", "Errors", "ErrorCellAddress")
    End With

    ' Early Binding - Add "Microsoft Scripting Runtime" Reference
        Dim FSO As New Scripting.FileSystemObject
    ' Set FolderPath
        Dim FolderPath As String
            FolderPath = "c:\Users\Desktop\Tryout\"' Set Folder FSO
        Dim Folder As Scripting.Folder
            Set Folder = FSO.GetFolder(FolderPath)

    ' Loop thru each file
        Dim File As Scripting.File
        Dim a As Range, b As Range, c As Range, d As Range, e As Range, f As Range, g As Range, h As Range, l As Range
            For Each File In Folder.Files

            Dim wkbData As Workbook
                Set wkbData = Workbooks.Open(File.Path)

            Dim wksData As Worksheet
                ActiveSheet.Name = "Control"
                Set wksData = wkbData.Worksheets("Control") ' -> Assume this file has only 1 worksheet

        'Format of the data
            Dim BlankRow As Long
                BlankRow = wks.Range("A"& wks.Rows.Count).End(xlUp).Row + 1

        ' Write filename in col E,F,G
            wks.Cells(BlankRow, 5).Value = File.Name
            wks.Cells(BlankRow, 6).Value = File.Name
            wks.Cells(BlankRow, 7).Value = File.Name

        'Find Testtest
            Set a = wksData.Columns("A:A").Find("  testtest         : ", LookIn:=xlValues)
        If Not a Is Nothing Then
            wks.Cells(BlankRow, 1).Value = a.Value
        End If

        'Find Temp
            Set b = wksData.Columns("A:A").Find("  testflyy         : ", LookIn:=xlValues)
        If Not b Is Nothing Then
            wks.Cells(BlankRow, 2).Value = b.Value
        End If

        'Find Type
            Set d = wksData.Columns("A:A").Find("  testflyy         : ", LookIn:=xlValues)
        If Not d Is Nothing Then
            wks.Cells(BlankRow, 3).Value = d.Value
        End If

        'Find start
            Set l = wksData.Columns("A:A").Find("  Started at: ", LookIn:=xlValues)
        If Not l Is Nothing Then
            wks.Cells(BlankRow, 4).Value = l.Value
        End If

        'Find Smart
            Set c = wksData.Columns("A:A").Find("SmartABC ", LookIn:=xlValues)
        If Not c Is Nothing Then
            wks.Cells(BlankRow, 9).Value = c.Value
        Else
            Set f = wksData.Columns("A:A").Find("SmarABCD Version ", LookIn:=xlValues)
        If Not f Is Nothing Then
            wks.Cells(BlankRow, 9).Value = f.Value
        Else
            Set g = wksData.Columns("A:A").Find("smarabcd_efg revision", LookIn:=xlValues)
        If Not g Is Nothing Then
            wks.Cells(BlankRow, 9).Value = g.Value
        End If
        End If
        End If

        'Find Errors
            Set e = wksData.Columns("A:A").Find("ERROR: ABC", LookIn:=xlValues)
        If Not e Is Nothing Then
            wks.Cells(BlankRow, 10).Value = e.Value
            wks.Cells(BlankRow, 11).Value = e.Address
        Else
            Set h = wksData.Columns("A:A").Find("ERROR: EFG", LookIn:=xlValues)
        If Not h Is Nothing Then
            wks.Cells(BlankRow, 10).Value = h.Value
        End If
        End If


        ' Trim and tidy up Data

    'Trim Testtest RowA(1)
    wks.Cells(BlankRow, 1).Replace What:="testtest         : ", Replacement:="", LookAt:=xlPart, _
        SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
        ReplaceFormat:=False

    'Trim StartTime RowD(4)
    wks.Cells(BlankRow, 4).Replace What:="  Started at: ", Replacement:="", LookAt:=xlPart, _
        SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
        ReplaceFormat:=False

    'Trim Temp RowB(2)
        Dim strSearchB As String, strSearchC As String
        Dim bCell As Range, cCell As Range
        Dim s2 As String, s3 As String
            strSearchB = "  testflow         : B"
            strSearchC = "  testflow         : M"

    Set bCell = wks.Cells(BlankRow, 2).Find(What:=strSearchB, LookIn:=xlFormulas, _
        LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
        MatchCase:=False, SearchFormat:=False)

    If Not bCell Is Nothing Then
        s2 = Split(bCell.Value, ":")(1)
        s2 = Mid(s2, 1, 3)
        bCell.Value = s2
    Else

    Set cCell = wks.Cells(BlankRow, 2).Find(What:=strSearchC, LookIn:=xlFormulas, _
        LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
        MatchCase:=False, SearchFormat:=False)

    If Not cCell Is Nothing Then
        s3 = Split(cCell.Value, ":")(1)
        s3 = Mid(s3, 10, 2)
        cCell.Value = s3
    End If
    End If

    'Trim Type RowC(3)
        Dim strSearchD As String, strSearchE As String
        Dim dCell As Range, eCell As Range
        Dim s4 As String, s5 As String
            strSearchD = "  testflow         : B"
            strSearchE = "  testflow         : M1947"

    Set dCell = wks.Cells(BlankRow, 3).Find(What:=strSearchD, LookIn:=xlFormulas, _
        LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
        MatchCase:=False, SearchFormat:=False)

    If Not dCell Is Nothing Then
        s4 = Split(dCell.Value, "_", 3)(2)
        s4 = Mid(s4, 1, 3)
        dCell.Value = s4
    Else

    Set eCell = wks.Cells(BlankRow, 3).Find(What:=strSearchE, LookIn:=xlFormulas, _
        LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
        MatchCase:=False, SearchFormat:=False)

    If Not eCell Is Nothing Then
        eCell.Value = "123"
    End If
    End If

    'Trim No RowF(6)
        Dim strSearchF As String
        Dim fCell As Range
        Dim s6 As String
            strSearchF = "homebeestrash_archivetreser"

    Set fCell = wks.Cells(BlankRow, 6).Find(What:=strSearchF, LookIn:=xlFormulas, _
        LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
        MatchCase:=False, SearchFormat:=False)

    If Not fCell Is Nothing Then
        s6 = Split(fCell.Value, "treser")(1)
        s6 = Mid(s6, 1, 2)
        fCell.Value = s6
    End If

    'Trim EndDate RowG(7)
        Dim strSearchG As String
        Dim gCell As Range
        Dim s7 As String
            strSearchG = "homebeestrash_archivetreser"

    Set gCell = wks.Cells(BlankRow, 7).Find(What:=strSearchG, LookIn:=xlFormulas, _
        LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
        MatchCase:=False, SearchFormat:=False)

    If Not gCell Is Nothing Then
        s7 = Split(gCell.Value, "reports")(1) 
        s7 = Split(s7, "Report")(0) 
        s7 = Left(s7, 8) & ""& Right(s7, 6) 
        'Month Row H(8)
        wks.Cells(BlankRow, 8).Value = WorksheetFunction.Transpose(Left(s7, 4) & "-"& Mid(s7, 5, 2) & "-"& Mid(s7, 7, 2)) 
        gCell.Value = s7
    End If
        wks.Cells(BlankRow, 8).NumberFormat = "[$-en-US]mmmm d, yyyy;@"'Set Date format

    'Trim Smart
        Dim strSearchST As String
        Dim stCell As Range
        Dim s8 As String
            strSearchST = "This is "

    Set stCell = wks.Cells(BlankRow, 9).Find(What:=strSearchST, LookIn:=xlFormulas, _
        LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
        MatchCase:=False, SearchFormat:=False)

    If Not stCell Is Nothing Then
        s8 = Split(stCell.Value, "This is ")(1)
        s8 = Mid(s8, 1, 29)
        stCell.Value = s8
    End If

    wkbData.Close False
    Next File

    'Add AutoFilter
    Dim StartDate As Long, EndDate As Long

    With wks.Cells(BlankRow, 8)
        StartDate = DateSerial(Year(.Value), Month(.Value), 1)
        EndDate = DateSerial(Year(.Value), Month(.Value) + 1, 0)
    End With

    wks.Cells(BlankRow, 8).AutoFilter Field:=5, Criteria1:=">="& StartDate, Operator:=xlAnd, Criteria2:="<="& EndDate
    If ActiveSheet.FilterMode Then ActiveSheet.ShowAllData

End Sub

Can anyone let me know how can i use the coding below and alter it to what my original code does. If possible maybe provide me a small part of the code so that i can understand and then continue myself or so that i can modify it myself.

Private Sub AddColumnHeaders(ByVal sheet As Worksheet)
    sheet.Range("A1:K1") = Array( _
         "Test", "Temp", "Type", "Start", _
         "FileName", "No", "End", "Month", _
         "Smart", "Errors", "ErrorCellAddress")
End Sub
Dim sheet As Worksheet
Set sheet = CreateOutputSheet(ActiveWorkbook)
Private Function CreateOutputSheet(ByVal book As Workbook) As Worksheet
    Dim sheet As Worksheet
    Set sheet = book.Worksheets.Add(After:=book.Worksheets(book.Worksheets.Count))
    AddColumnHeaders sheet
    Set CreateOutputSheet = sheet
End Function
Dim basePath As String
basePath = Environ$("USERPROFILE") & "\Desktop\Tryout\"

Dim baseFolder As Scripting.Folder
With New Scripting.FileSystemObject
    Set baseFolder = .GetFolder(basePath)
End With
Dim table As ListObject
Set table = wks.ListObjects("TableName")

Dim newRow As ListRow
Set newRow = table.ListRows.Add
Private Function PopulateIfFound(ByVal source As Range, ByVal value As String, ByVal row As ListRow, ByVal writeToColumn As Long, Optional ByVal writeAddressToNextColumn As Boolean = False) As Boolean
    Dim result As Range
    Set result = source.Find(value, LookIn:=xlValues)
    If Not result Is Nothing Then
        Dim cell As Range
        Set cell = row.Range.Cells(ColumnIndex:=writeToColumn)
        cell.Value = result.Value
        If writeAddressToNextColumn Then
            cell.Offset(ColumnOffset:=1).Value = result.Address
        End If
        PopulateIfFound = True
    End If
End Function
  Dim source As Range
    Set source = wksData.Range("A:A")

    PopulateIfFound source, "  testtest         : ", newRow, 1
    PopulateIfFound source, "  testflyy         : ", newRow, 2
    PopulateIfFound source, "  testflyy         : ", newRow, 3
    PopulateIfFound source, "  Started at: ", newRow, 4
    If Not PopulateIfFound(source, "SmartABC ", newRow, 9) Then
        PopulateIfFound source, "smarabcd_efg revision", newRow, 9
    End If
    If Not PopulateIfFound(source, "ERROR: ABC", newRow, 10, True) Then
        PopulateIfFound source, "ERROR: EFG", newRow, 10
    End If

Irregular #1004 error on Worksheet.[Pictures./Range.]Paste

$
0
0

Macro goal: screenshots making of windows desktop application.

Macro fails irregularly in last shown line of sub:

Sub MakeScreenShot()
    ...
    ClearClipboard
    AltPrintScreen
    wsShots.Activate
    wsShots.Range("B2").Select
    wsShots.Pictures.Paste
    ...
End sub

Found that:

  • 1004 error happens due to empty clipboard
  • in most cases right after error is occurred (when VBE is highlighting the error line) on switching to Excel UI can see that clipboard is not empty
  • on pasting clipboard then can see screenshot of VBE window with highlighted yellow line
  • error happening is highly correlated with PC CPU usage over 40-50% (re-searched by Task Manager)

Assumption: due to clipboard content (VBE screenshot) on error happening, it looks like in some cases WinAPI calls (keybd_event) stuck (by what reason?) in some queue and OS sends it back to VBE. Tried to add Sleep and/or DoEvents right after AltPrintScreen, didnt find the difference.

Definition for AltPrintScreen:

Public Declare PtrSafe Sub KeybdEvent Lib "user32" Alias "keybd_event" (ByVal bVk As Byte, ByVal bScan As Byte, ByVal dwFlags As Long, ByVal dwExtraInfo As Long)
Enum KeybdEventEnum
    KEYEVENTF_KEYUP = &H2
    VK_SNAPSHOT = &H2C
    VK_MENU = &H12
End Enum

Sub AltPrintScreen()
    KeybdEvent VK_MENU, 0, 0, 0
    KeybdEvent VK_SNAPSHOT, 0, 0, 0
    KeybdEvent VK_SNAPSHOT, 0, KEYEVENTF_KEYUP, 0
    KeybdEvent VK_MENU, 0, KEYEVENTF_KEYUP, 0
    Sleep 50
End Sub

Please assist; this makes me crazy, it takes several days to localize the issue.

How to extract hyperlink from Outlook mail to Excel?

$
0
0

I am trying to extract a hyperlink. There are several hyperlinks in the mail but this link is to download a file and it contains the word "download".

I receive several mails in the same mail format in a day. This is why I need to automate the downloading process.

As the first step, I extract the required link to Excel with below code in two modules

Module 1

Dim objExcelApp As Excel.Application
Dim objExcelWorkbook As Excel.Workbook
Dim objExcelWorksheet As Excel.Worksheet

Sub ExportAllHyperlinksInMultipleEmailsToExcel()
Dim objSelection As Selection
Dim objMail As MailItem
Dim objMailDocument As Document
Dim objHyperlink As Hyperlink
Dim i As Long
Dim s As String

Set objSelection = Outlook.Application.ActiveExplorer.Selection

If Not (objSelection Is Nothing) Then

   Set objExcelApp = CreateObject("Excel.Application")
   Set objExcelWorkbook = objExcelApp.Workbooks.Add
   Set objExcelWorksheet = objExcelWorkbook.Sheets(1)
   objExcelApp.Visible = True
   objExcelWorkbook.Activate

   With objExcelWorksheet
        .Cells(1, 1) = "No."
        .Cells(1, 2) = "Address"

  End With

  On Error Resume Next
  i = 0
  For Each objMail In objSelection
      objMail.Display
      Set objMailDocument = objMail.GetInspector.WordEditor
      If objMailDocument.Hyperlinks.Count > 0 Then
         For Each objHyperlink In objMailDocument.Hyperlinks
              If InStr(10, objHyperlink.Address, "download") > 40 Then
                i = i + 1
                s = CStr(objHyperlink.Address)
                Call Module2.ExportToExcel(i, s, objExcelWorksheet)
             End If
         Next
      End If
      objMail.Close olDiscard
  Next
End If
End Sub

Module 2

  Sub ExportToExcel(n As Long, j As String, objExcelWorksheet AsExcel.Worksheet)

 Dim nLastRow As Integer

nLastRow = objExcelWorksheet.Range("A"& objExcelWorksheet.Rows.Count).End(xlUp).Row + 1

objExcelWorksheet.Range("A"& nLastRow).Value = CStr(n)
objExcelWorksheet.Range("B"& nLastRow).Value = j

End Sub

The code runs but the generated Excel shows the values in Column A only (Mail No.). Column B, which should have the address of the hyperlink, remains blank.


Parsing destroyed table from ms word

Import Visual Basic text inputs into Excel Spreadsheet

$
0
0

So I have the visual basic side of it all covered with the input stuff and dims all written by me and Microsoft.Office.Interop.Excel.Application stuff added from a Microsoft VB reference. The VB has no errors but I still cannot figure out how to get the inputs put into the oSheet.Cells(1, 2).Value = txtCustomer.Text input to go to Excel. I do not see any option to add the Excel spreadsheet to VB. I tried going through Excel Developer mode to import VB code but it would not let me save my VB code properly so I would rather keep the VB where it is. Here is the VB code

Public Class Form1

    Private Sub BtnCalc_click(sender As Object, e As EventArgs) Handles BtnCalc.Click

        Dim stringDate As String
        Dim house, roof, paver, drive As Integer
        Dim dblhouse, dblroof, dblpaver, dbldrive As Double
        Dim dbllocale As Double
        Dim tax As Integer
        Dim customer As String

        customer = txtCustomer.Text
        stringDate = TxtDate.Text
        Dim LstSize As String
        Dim dbltotal As Double
        Dim location As Integer

        '''house sizes

        If location = "1800" Then
            dbllocale = 1.0
        End If

        If location = "2400" Then
            dbllocale = 1.2
        End If

        If location = "3000" Then
            dbllocale = 1.65
        End If

        If location = "4000" Then
            dbllocale = 2.2
        End If

        ''checks for which parts of the house get power washed
        If ChkCredit.Checked = True Then
            tax = 1.07
        Else
            tax = 1
        End If

        ''check for house
        If Chkhouse.Checked = True Then
            house = 1
        Else
            house = 0
        End If

        ''check for roof
        If ChkRoof.Checked = True Then
            roof = 1
        Else
            roof = 0
        End If

        ''check for pavers/sidewalks
        If ChkPaver.Checked = True Then
            paver = 1
        Else
            paver = 0
        End If

        ''check for driveways/large patios
        If ChkDrive.Checked = True Then
            drive = 1
        Else
            drive = 0
        End If

        dblhouse = (house * 350.0) * (dbllocale)
        dblroof = (roof * 450.0) * (dbllocale)
        dblpaver = (paver * 125.0)
        dbldrive = (drive * 165.0)
        dbltotal = tax * ((dblhouse) + (dblroof) + (dblpaver) + (dbldrive))
        TxtTotal.Text = (dbltotal)
    End Sub

    Private Sub ListBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles LstSize.SelectedIndexChanged
        Location = LstSize.SelectedItem
    End Sub

    Private Sub btnClose_Click(sender As Object, e As EventArgs) Handles BtnClose.Click
        Me.Close()
        'closes application
    End Sub

    Private Sub btnClear_Click(sender As Object, e As EventArgs) Handles BtnClear.Click
        txtCustomer.Text = ""
        Chkhouse.Checked = False
        ChkRoof.Checked = False
        ChkPaver.Checked = False
        ChkDrive.Checked = False
        TxtTotal.Text = ""
        ChkCredit.Checked = False
        'clears text boxes and total text
    End Sub

    Private Sub Label1_Click(sender As Object, e As EventArgs) Handles Label1.Click
    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)

        Try

            Dim oXL As Microsoft.Office.Interop.Excel.Application
            Dim oWB As Microsoft.Office.Interop.Excel.Workbook
            Dim oSheet As Microsoft.Office.Interop.Excel.Worksheet
            Dim oRng As Microsoft.Office.Interop.Excel.Range


            'On Error GoTo Err_Handler
            ' Start Excel and get Application object.
            oXL = CreateObject("Excel.Application")
            oXL.Visible = True

            ' Get a new workbook.
            oWB = oXL.Workbooks.Add
            oSheet = oWB.ActiveSheet

            ' Add cells by looping.
            Dim iRow As Integer = 1
            For iRow = 1 To 10
                oSheet.Cells(iRow, 1).Value = "Test"& iRow
            Next iRow

            '//Create an Array and then add these entries to an excel spreadsheet
            Dim a(10) As String
            For iRow = 1 To 10
                a(iRow) = "Array Entry"& iRow.ToString
            Next

            '//Add to sheet
            For iRow = 1 To 10
                oSheet.Cells(iRow, 2).Value = a(iRow)
            Next iRow

            '//Add from a textbox Control
            oSheet.Cells(1, 2).Value = txtCustomer.Text

            ' Make sure Excel is visible and give the user control
            ' of Microsoft Excel's lifetime.
            oXL.Visible = True
            oXL.UserControl = True

            ' Make sure you release object references.
            oRng = Nothing
            oSheet = Nothing
            oWB = Nothing
            oXL = Nothing
        Catch ex As Exception
            MsgBox(Err.Description, vbCritical, "Error: "& Err.Number)

        End Try
    End Sub
End Class```


VBA: Copy & Paste data from source workbook to destination worksheet If their Cell "A1" value is equal to each others

$
0
0

-I have 2 workbooks now, one is the source, another one is the destination.

-They have the same format, but only the source file contains data

-Both workbooks have the same TABs (But the Tabs are variables, For example, Tab A, B, C are created this time, but next time they might be Tab C, D, E)

  • I would like to have something like this:

I have already set wb1 (Source) & wb2 (Destination) As those 2 workbooks

Dim ws As worksheet
 If wb1.ws.Name = wb2.ws.Name Then

Copy & paste the same Tab info. (Range A1 to last row) from wb1 to wb2

  • But somehow the code is not supported by VBA. What is the correct code that I can set

Thanks!

`Sub Macro1()

' Copy & paste from workbook to workbook

Dim Wb1 As Excel.Workbook Set Wb1 = Application.Workbooks("Test Template")enter code here Dim Wb2 As Excel.Workbook Set Wb2 = Application.Workbooks("Hy.xlsm")

Set ws1 = Wb1.Worksheets Set ws2 = Wb2.Worksheets

If ws1.Name = ws2.Name Then MsgBox "True" End If

End Sub

How to delete export excel empty rows in jquery

$
0
0

I export excel file this code blocks but the first two lines are empty in export excel and I want to delete this two emty rows How can I delete those rows. Thanks

function JSONToCSVConvertor(JSONData, ReportTitle, ShowLabel) {
    var arrData = typeof JSONData != 'object' ? JSON.parse(JSONData) : JSONData;
    var CSV = '';
    CSV += ReportTitle + '\r\n\n';
    if (ShowLabel) {
        var row = "";

        for (var index in arrData.data2[0]) {
            row += index + ',';
        }
        row = row.slice(0, -1);
        CSV += row + '\r\n';
    }

    for (var i = 0; i < arrData.data2.length; i++) {
        var row = "";

        for (var index in arrData.data2[i]) {
            row += '"' + arrData.data2[i][index] + '",';
        }
        row.slice(0, row.length - 1);
        delete row[1][1];
        CSV += row + '\r\n';
    }
    if (CSV == '') {
        alert("error");
        return;
    }
    var fileName = "MyExcel";
    fileName += ReportTitle.replace(/ /g, "_");
    var a = window.document.createElement('a');
    var uri = 'data:text/csv;charset=utf-8,%EF%BB%BF' + encodeURIComponent(CSV);        
    var link = document.createElement("a");
    link.href = uri;
    link.style = "visibility:hidden";
    link.download = fileName + ".csv";
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
}

R: cannot run specific cmd code that converts .xls to .xlsx

$
0
0

Long time reader, first time writter...

Im writting some R code that shall take some data input from other sources. One place can only give data as a .xls format. While there is good excel capabilities in R, this .xls file cannot be read from R. But if i convert it to .xlsx R handels it fine. So im gonna convert it.

In a direct cmd input, i cann convert it by doing as below:

"C:/Program Files (x86)/Microsoft Office/root/Office16/excelcnv.exe" -oice "C:/Users/my_name/OneDrive - work/Documents/Dashboard code/New Code/work_STD_TEMPLATE.xls""C:/Users/my_name/OneDrive - work/Documents/Dashboard code/New Code/work_STD_TEMPLATE2.xlsx"

But I wish to automate the code, so implementing this would be best. See below for the version i can compile and run.

R-code:

args = c("C:/Program Files (x86)/Microsoft Office/root/Office16/excelcnv.exe" , 
         '-oice' , "C:/Users/my_name/OneDrive - work/Documents/Dashboard code/New Code/work_STD_TEMPLATE.xls" , "C:/Users/my_name/OneDrive - work/Documents/Dashboard code/New Code/work_STD_TEMPLATE2.xlsx");
system2(args)

But while it runs it stalls the system and finally promts a pop-upbox that tells me:

excelcnv.exe - Application Error The application was unable to start correctly (0x0000142).

I need big brain person for this. Thanks in advance

Found answer last night:

 args = "\"C:\\Program Files (x86)\\Microsoft Office\\root\\Office16\\excelcnv.exe\" -oice \"C:\\Users\\my_name\\OneDrive - work\\Documents\\Dashboard code\\New Code\\work_STD_TEMPLATE.xls\" \"C:\\Users\\my_name\\OneDrive - work\\Documents\\Dashboard code\\New Code\\work_STD_TEMPLATE2.xlsx\""
   system("cmd.exe" , input = args)

I needed to escape charterer the escape characters... so \ had to be \ and " had to be \"

Viewing all 89226 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>