<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>range Archive - Robert Skibbe</title>
	<atom:link href="https://robbelroot.de/blog/tag/range/feed/" rel="self" type="application/rss+xml" />
	<link></link>
	<description>alias RobbelRoot – Freelance Full Stack Developer .NET</description>
	<lastBuildDate>Thu, 18 Jan 2024 00:55:31 +0000</lastBuildDate>
	<language>de</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.9.4</generator>

<image>
	<url>https://robbelroot.de/wp-content/uploads/2020/12/cropped-favicon-32x32.png</url>
	<title>range Archive - Robert Skibbe</title>
	<link></link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>C# Bluetooth example – searching &#038; listing devices in 2024</title>
		<link>https://robbelroot.de/blog/csharp-bluetooth-example-searching-listing-devices/</link>
					<comments>https://robbelroot.de/blog/csharp-bluetooth-example-searching-listing-devices/#comments</comments>
		
		<dc:creator><![CDATA[Robert Skibbe]]></dc:creator>
		<pubDate>Tue, 12 Jul 2022 23:22:59 +0000</pubDate>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[C# HowTo's]]></category>
		<category><![CDATA[General]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[32feet]]></category>
		<category><![CDATA[bluetooth]]></category>
		<category><![CDATA[c sharp]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[client]]></category>
		<category><![CDATA[csharp]]></category>
		<category><![CDATA[device]]></category>
		<category><![CDATA[devices]]></category>
		<category><![CDATA[example]]></category>
		<category><![CDATA[inthehand]]></category>
		<category><![CDATA[list]]></category>
		<category><![CDATA[range]]></category>
		<category><![CDATA[scan]]></category>
		<category><![CDATA[search]]></category>
		<guid isPermaLink="false">https://robbelroot.de/?p=10423</guid>

					<description><![CDATA[<p>A simple C# Bluetooth example A simple and easy to use C# bluetooth example, this was the thing I was looking for in the last days. I needed it for my remake of my logistics software called &#8222;Motraso&#8220;, but let&#8217;s talk about that in a second. We will talk about &#8230;</p>
<p>Der Beitrag <a href="https://robbelroot.de/blog/csharp-bluetooth-example-searching-listing-devices/">C# Bluetooth example – searching &#038; listing devices in 2024</a> erschien zuerst auf <a href="https://robbelroot.de">Robert Skibbe</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<figure class="wp-block-image size-full"><a href="https://robbelroot.de/wp-content/uploads/2022/07/C-Bluetooth-Example-Listing-devices.png"><img fetchpriority="high" decoding="async" width="1200" height="628" src="https://robbelroot.de/wp-content/uploads/2022/07/C-Bluetooth-Example-Listing-devices.png" alt="C# Bluetooth Example - Listing devices" class="wp-image-10541" title="C# Bluetooth Example - Listing devices"/></a><figcaption class="wp-element-caption">C# Bluetooth Example &#8211; Listing devices</figcaption></figure>






<h2 class="wp-block-heading">A simple C# Bluetooth example</h2>



<p>A simple and easy to use C# bluetooth example, this was the thing I was looking for in the last days. I needed it for my remake of my logistics software called &#8222;Motraso&#8220;, but let&#8217;s talk about that in a second. We will talk about the basic functionality considering the creation of a simple &#8222;BluetoothClient&#8220; instance, which is able to list devices and more. I will also add some more functionality in a later post, or edit this one &#8211; stay tuned!</p>



<p>Maybe you want to take a look at my <strong><a href="https://robbelroot.de/blog/a-bluetooth-phone-call-in-csharp-and-vbnet/" target="_blank" rel="noreferrer noopener">blog post considering an actual bluetooth call on your phone</a></strong> as well?</p>



<p class="info-banner">&#x1f4a1; No time? No problem! If you need a quick code snippet on how to list available bluetooth devices, just go to <strong><a href="#searching-for-bluetooth-devices-async">the important functions</a></strong>. Don&#8217;t forget to install the mentioned library <strong><a href="#installing-32feet-lib">here</a></strong>. Alternatively, go ahead and download one of the examples at the bottom of the page.</p>



<style>
.info-banner {
  background: #8acc47;
  padding: 2em;
  border-radius: 0.5em;
  color: whitesmoke;
}

.info-banner a {
 color: #2E86AB !important; 
}
</style>



<h2 class="wp-block-heading">Prefering videos? Gotcha back!</h2>



<p>In case you don&#8217;t want to read the text, here is an example with a Windows Forms Bluetooth application as video format. Keep in mind, that the blog post contains more details like with WPF, etc. &#8211; which is not covered in the video.</p>


<div class="async-youtube" data-embed="YJuiLyy905M" data-alt="">
    <div class="play-button"></div>      
  </div>



<h2 class="wp-block-heading">My app needed a bluetooth upgrade</h2>



<p>So in my current remake of my logistics software &#8222;Motraso&#8220;, I wanted the user to be able to make a direct call through their app. Speaking about &#8222;direct&#8220;, I&#8217;m meaning the actual dial process without further interaction from the user &#8211; yay! So far, the webapp-version did something similar by just providing some hyperlinks with the corresponding <strong>a</strong>-tags.</p>



<p>This kind of behaviour is implemented in like every webbrowser-capable device by providing for example an email link:</p>



<pre class="wp-block-code"><code>&lt;a href="mailto:john.doe@thedomain.com"&gt;The text you want the user to see..&lt;/a&gt;</code></pre>



<p>Which would look like this here (no click intended..):</p>



<a href="mailto:john.doe@thedomain.com">The text you want the user to see..</a>



<p></p>



<p>Basically, this is pretty neat, as it&#8217;s supported in almost every modern device, but usually there will be some kind of confirmation. This also counts for the desired phone dial approach, which essentially works in the same manner:</p>



<pre class="wp-block-code"><code>&lt;a href="tel:1234567890"&gt;Maybe display the phone number, or an icon..&lt;/a&gt;</code></pre>



<p>Preview:</p>



<a href="tel:1234567890">Maybe display the phone number, or an icon..</a>



<p></p>



<p>This is not what I wanted – meh.. I wanted to provide some nice functionality to my users, where they can only click a button and voila &#8211; the device (like a phone, etc.) will just call that number. No need for user interaction, no special permissions, nothing! This is where I came up with another idea, using bluetooth!</p>



<p>I mean seriously, who wants to pull out his phone out of his pocket, just to say: &#8222;Yes, I REALLY want to call this guy using bluetooth&#8220;. So I&#8217;m pretty glad I stumbled upon the following library.</p>



<h2 class="wp-block-heading">Library search and installation – C# Bluetooth example</h2>



<figure class="wp-block-image size-full"><a href="https://robbelroot.de/wp-content/uploads/2022/07/C-Bluetooth-example-Much-work-little-time.jpg"><img decoding="async" width="1280" height="960" src="https://robbelroot.de/wp-content/uploads/2022/07/C-Bluetooth-example-Much-work-little-time.jpg" alt="C# Bluetooth example - Much work, little time" class="wp-image-10435" title="C# Bluetooth example - Much work, little time"/></a><figcaption class="wp-element-caption">C# Bluetooth example &#8211; much work, little time</figcaption></figure>



<p>So as always – time&#8217;s short, work being much – I thought about browsing some of the known sources for developers. For sure I did hit Stackoverflow (who would&#8217;ve thought of that..) and – as a .NET Dev – I did take a look into the NuGet packages. Pretty fast, I&#8217;ve found a big and nice library which I can actually remember working with in the past.</p>



<p>At that time I was working on a project for one of my former employers, which needed to connect to a machine measuring the kick-speed of a football player for a sports event. Yeah, yeah, I hear you – that&#8217;s another story, so back to topic. The library I&#8217;m talking about is called &#8222;<strong><a href="https://github.com/inthehand/32feet" target="_blank" rel="noreferrer noopener">InTheHand.32feet</a></strong>&#8222;.</p>



<p>My best bet was, to just install that library and try out some things and it worked so far. Later, when I actually went to dialing, etc. this was a bit more of a headache, but this will be content for another post (or an edit/update). So for now, you can go ahead and actually install the mentioned library by using the following steps.</p>



<h3 class="wp-block-heading" id="installing-32feet-lib">Creating a new project, installing the 32feet lib </h3>



<p>Open a new Visual Studio project (or use your existing one&#8230;) and make a right click on your project name on the right side, it should be listed inside the project folder explorer. Take care to actually hit the project itself, not the overview thingy. Please don&#8217;t get confused, as this is a german-named test-project for one of my customers. Just click the item with that little green C# icon in front of its text contents.</p>



<figure class="wp-block-image size-full"><a href="https://robbelroot.de/wp-content/uploads/2022/07/C-Bluetooth-Example-Right-clicking-the-project-name-inside-the-project-folder-explorer.png"><img decoding="async" width="269" height="354" src="https://robbelroot.de/wp-content/uploads/2022/07/C-Bluetooth-Example-Right-clicking-the-project-name-inside-the-project-folder-explorer.png" alt="C# Bluetooth Example - Right clicking the project name inside the project folder explorer" class="wp-image-10445" title="C# Bluetooth Example - Right clicking the project name inside the project folder explorer"/></a><figcaption class="wp-element-caption">C# Bluetooth Example &#8211; Right clicking the project name inside the project folder explorer</figcaption></figure>



<p>Now this context menu will appear, where you can click on the &#8222;Manage NuGet packages&#8220;-item (sorry, german as well..):</p>



<figure class="wp-block-image size-full"><a href="https://robbelroot.de/wp-content/uploads/2022/07/C-Bluetooth-Example-Manage-NuGet-packages-for-project.png"><img loading="lazy" decoding="async" width="377" height="647" src="https://robbelroot.de/wp-content/uploads/2022/07/C-Bluetooth-Example-Manage-NuGet-packages-for-project.png" alt="Manage NuGet packages for project" class="wp-image-10447" title="Manage NuGet packages for project"/></a><figcaption class="wp-element-caption">Manage NuGet packages for project</figcaption></figure>



<figure class="wp-block-image size-full"><a href="https://robbelroot.de/wp-content/uploads/2022/07/C-Bluetooth-Example-Installing-32feet-Library.png"><img loading="lazy" decoding="async" width="977" height="554" src="https://robbelroot.de/wp-content/uploads/2022/07/C-Bluetooth-Example-Installing-32feet-Library.png" alt="Installing 32feet Library" class="wp-image-10450" title="Installing 32feet Library"/></a><figcaption class="wp-element-caption">Installing 32feet Library</figcaption></figure>



<p>To finish up installing the needed library, just go ahead and search for &#8222;32feet&#8220; in the box &#8222;1&#8220;. Then choose the correct package marked with &#8222;2&#8220; and finally click &#8222;install&#8220; on the right side, which should be number &#8222;3&#8220;. After the installation process has finished without any errors, you should be able to use the corresponding classes, functions and etc.</p>



<p>If the NuGet paket manager doesn&#8217;t display the check mark thingy right away, just refresh or close and open it up again. This is some kind of pretty well known bug inside the package list, so no need to panic.</p>



<h2 class="wp-block-heading">Searching for bluetooth devices</h2>



<p>In the last/main step, we are going to actually search for devices. To be able to do so, you need to create an instance of the &#8222;BluetoothClient&#8220;-class, which is inside the &#8222;InTheHand.Net.Sockets&#8220;-namespace. Keep in mind, that I&#8217;m using the shortcut / inference styled initialization  syntax for the variables. You can do it like this:</p>



<h3 class="wp-block-heading">Instantiating the BluetoothClient</h3>



<pre class="EnlighterJSRAW" data-enlighter-language="csharp" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="C#" data-enlighter-group="bluetooth-client-instantiation">var bluetoothClient = new BluetoothClient();</pre>



<pre class="EnlighterJSRAW" data-enlighter-language="visualbasic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="VB.NET" data-enlighter-group="bluetooth-client-instantiation">Dim bluetoothClient = new BluetoothClient()</pre>



<p>If you prefer that explicit writing style (which I only do, when the concrete type isn&#8217;t obvious enough &#8211; but that&#8217;s like personal preference), just take a look at the next example. I just like that &#8222;keep it smart and simple&#8220; thing, you know!?</p>



<pre class="EnlighterJSRAW" data-enlighter-language="csharp" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="C#" data-enlighter-group="bluetooth-client-instantiation2">BluetoothClient bluetoothClient = new BluetoothClient();</pre>



<pre class="EnlighterJSRAW" data-enlighter-language="visualbasic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="VB.NET" data-enlighter-group="bluetooth-client-instantiation2">Dim bluetoothClient As BluetoothClient = new BluetoothClient()</pre>



<h3 class="wp-block-heading">Searching for devices</h3>



<p>To start the actual search for bluetooth devices, you need to call the &#8222;DiscoverDevices&#8220; function, of the &#8222;BluetoothClient&#8220;-instance. This will return an Array of the &#8222;BluetoothDeviceInfo&#8220;-class. Keep in mind, that this can be some kind of laggy, but we will fix this as well, soon:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="csharp" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="C#" data-enlighter-group="searching-for-bluetooth-devices">var bluetoothDevices = bluetoothClient.DiscoverDevices();</pre>



<pre class="EnlighterJSRAW" data-enlighter-language="visualbasic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="VB.NET" data-enlighter-group="searching-for-bluetooth-devices">Dim bluetoothDevices = bluetoothClient.DiscoverDevices()</pre>



<p class="info-banner">&#x1f4a1; Give the search process some time. If it&#8217;s too slow for you, try tweaking with the available parameters of the &#8222;DiscoverDevices&#8220; function. We will make that laggy feeling go away as well, soon.</p>



<p id="searching-for-bluetooth-devices-async">To make it less laggy, we can actually delegate it to the &#8222;<strong><a href="https://docs.microsoft.com/en-us/dotnet/api/system.threading.tasks.task.run?view=net-6.0" target="_blank" rel="noreferrer noopener">Task.Run</a></strong>&#8220; helper function and use the return value of that &#8211; making it async. Keep in mind to use it in an async context, meaning like an async marked Task itself.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="csharp" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="C#" data-enlighter-group="searching-for-bluetooth-devices-async">public async Task&lt;BluetoothDeviceInfo[]> SearchDevicesAsync()
{
  var bluetoothClient = new BluetoothClient();
  var bluetoothDevices = await Task.Run(() => bluetoothClient.DiscoverDevices());
  bluetoothClient.Close();
  return bluetoothDevices;
}</pre>



<pre class="EnlighterJSRAW" data-enlighter-language="visualbasic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="VB.NET" data-enlighter-group="searching-for-bluetooth-devices-async">Public Function SearchDevicesAsync() As BlutoothDeviceInfo()
  Dim bluetoothClient = New BluetoothClient()
  Dim bluetoothDevices = Await Task.Run(Function() bluetoothClient.DiscoverDevices())
  bluetoothClient.Close()
  Return bluetoothDevices
End Function</pre>



<p>Maybe you could improve further by making use of the using statement, instead of closing the bluetooth client manually. Currently I&#8217;m elaborating on the reuse of the Bluetooth client, so maybe you can update me here as well, if you&#8217;ve found out interesting stuff!</p>



<h2 class="wp-block-heading">Implementation inside a C# Winforms App</h2>



<figure class="wp-block-image size-full"><a href="https://robbelroot.de/wp-content/uploads/2022/07/Windows-Forms-C-Bluetooth-Example-Application.png"><img loading="lazy" decoding="async" width="571" height="401" src="https://robbelroot.de/wp-content/uploads/2022/07/Windows-Forms-C-Bluetooth-Example-Application.png" alt="Windows Forms C# Bluetooth Example Application" class="wp-image-10482" title="Windows Forms C# Bluetooth Example Application"/></a><figcaption class="wp-element-caption">Windows Forms C# Bluetooth Example Application</figcaption></figure>



<p>As always, I&#8217;d like to provide a nice, working and &#8222;ready to use&#8220; example, you are welcome to download it further below. At first we will take a look at a Windows Forms application (with C#, but I mean you can easily translate the code with the above help..).</p>



<p>So go ahead and create a new Windows Forms App, use the NET Version 6 and install the library as explained above. If you&#8217;ve finished those steps, we can go further on creating the Windows Forms App / UI. As I personally pretty much hate laggy sh** I will of course use an asynchronous approach.</p>



<h3 class="wp-block-heading">The UI</h3>



<p>Inside this Windows Forms App considering a C# Bluetooth example, I will use two basic list variations, searching and listing our bluetooth results. One will be more or less self-implemented, the other one is a basic &#8222;ListBox&#8220;-control. Add a &#8222;FlowLayoutPanel&#8220; with a size of like 289 x 241 and a &#8222;ListBox&#8220; with a size of  179 x 244 to your form. Next take a button and name those controls in a nice manner as you always should.</p>



<h3 class="wp-block-heading">The Code</h3>



<p>Now we are going to add some code to our Winforms C# Bluetooth example application. At first we will create some temporary data stores for our values / class instances. Notice, that I&#8217;m using the newer filescope namespace syntax, as I love saving unnecessary spaces.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="csharp" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">using BluetoothExampleWinformsDeviceSearchCS.Controls;
using InTheHand.Net.Sockets;

namespace BluetoothExampleWinformsDeviceSearchCS;

public partial class Form1 : Form
{

    List&lt;BluetoothDeviceInfo> _bluetoothDevices;

    bool _isSearchingForDevices;

    public bool IsSearchingForDevices
    {
        get => _isSearchingForDevices;
        set
        {
            _isSearchingForDevices = value;
            btnScanForDevices.Enabled = !_isSearchingForDevices;
        }
    }

    // more to come..

}</pre>



<p>Create a constructor for the form in the next step, this will initialize the device data store and configure the &#8222;ListBox&#8220;.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="csharp" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">    public Form1()
    {
        InitializeComponent();
        _bluetoothDevices = new List&lt;BluetoothDeviceInfo>();
        lbBluetoothDevices.DisplayMember = "DeviceName";
    }</pre>



<p>Next, go inside the click handler of the button (with double clicking it inside the designer, or using another method) and use the following code. Keep in mind, that we are using the <strong><a href="#searching-for-bluetooth-devices-async">code already provided </a></strong>above, as well. At first we will set our busy flag, to indicate – well – that we are busy. Then we are clearing potential leftovers from a previous run.</p>



<p>After that, we are fetching our bluetooth devices and add them to our backing store all at once. If it fails for whatever reason, we will output a message containing the details. At last, we will render our UI and set the searching flag to false.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="csharp" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">    private async void btnScanForDevices_Click(object sender, EventArgs e)
    {
        IsSearchingForDevices = true;
        _bluetoothDevices.Clear();
        flpBluetoothDevices.Controls.Clear();
        lbBluetoothDevices.Items.Clear();
        try
        {
            var bluetoothDevices = await SearchDevicesAsync();
            _bluetoothDevices.AddRange(bluetoothDevices);
        }
        catch (Exception ex)
        {
            MessageBox.Show($"Couldn't search for bluetooth devices: {ex.Message}");
        }
        if (_bluetoothDevices.Count > 0)
        {
            DisplayFlpItems();
            DisplayLbItems();
        }
        IsSearchingForDevices = false;
    }</pre>



<p>Both methods caring about the UI lists look like this. I also added the little handler function which gets connected dynamically. Don&#8217;t forget to kill those handler when closing the form, I&#8217;m doing this in the last method.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="csharp" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">    private void DisplayFlpItems()
    {
        foreach (var device in _bluetoothDevices)
        {
            var bluetoothDeviceItem = new BluetoothDeviceItem(device);
            bluetoothDeviceItem.Click += BluetoothDeviceItem_Click;
            flpBluetoothDevices.Controls.Add(bluetoothDeviceItem);
        }
    }

    private void BluetoothDeviceItem_Click(object? sender, EventArgs e)
    {
        var deviceItem = sender as BluetoothDeviceItem;
        var device = deviceItem!.Device;
        MessageBox.Show($"You clicked on device: {device!.DeviceName}");
    }

    private void DisplayLbItems()
    {
        lbBluetoothDevices.DataSource = null;
        lbBluetoothDevices.DataSource = _bluetoothDevices;
    }

    private void Form1_FormClosing(object sender, FormClosingEventArgs e)
    {
        if (flpBluetoothDevices.Controls.Count > 0)
        {
            foreach (var bluetoothDeviceItem in flpBluetoothDevices.Controls.OfType&lt;BluetoothDeviceItem>())
            {
                bluetoothDeviceItem.Click -= BluetoothDeviceItem_Click;
            }
        }
    }</pre>



<h3 class="wp-block-heading">Last step &#8211; our little custom UserControl</h3>



<p>To improve the visualization of the items a bit (well, in terms of Winforms..), I created a small &#8222;UserControl&#8220; holding some information. It will contain the name and the bluetooth address of the corresponding device. You can create a new subfolder in your project called &#8222;Controls&#8220; and add a new &#8222;UserControl&#8220; there. I will call it &#8222;BluetoothDeviceItem&#8220;.</p>



<p>Add two labels, style them in your favour and don&#8217;t forget to change the &#8222;AutoSize&#8220; property to &#8222;false&#8220;, with an explicit width. You can avoid overflowing the control this way. The control could look like this for example:</p>



<figure class="wp-block-image size-full"><a href="https://robbelroot.de/wp-content/uploads/2022/07/Bluetooth-Windows-Forms-App-UserControl.png"><img loading="lazy" decoding="async" width="279" height="138" src="https://robbelroot.de/wp-content/uploads/2022/07/Bluetooth-Windows-Forms-App-UserControl.png" alt="Bluetooth Windows Forms App UserControl" class="wp-image-10508" title="Bluetooth Windows Forms App UserControl"/></a><figcaption class="wp-element-caption">Bluetooth Windows Forms App UserControl</figcaption></figure>



<h2 class="wp-block-heading">Implementation inside a C# WPF MVVM App</h2>



<figure class="wp-block-image size-full"><a href="https://robbelroot.de/wp-content/uploads/2022/07/WPF-MVVM-Bluetooth-Example-App.png"><img loading="lazy" decoding="async" width="835" height="547" src="https://robbelroot.de/wp-content/uploads/2022/07/WPF-MVVM-Bluetooth-Example-App.png" alt="WPF MVVM Bluetooth Example App" class="wp-image-10529" title="WPF MVVM Bluetooth Example App"/></a><figcaption class="wp-element-caption">WPF MVVM Bluetooth Example App</figcaption></figure>



<p>Next we will take a look on how this could look inside a more modern WPF MVVM App. Even though MVVM being a personal preference, you should be able to easily switch out necessary components. Another thing would be, that I will actually use some of my favourite WPF Tools for the app, so skip what you don&#8217;t want / need out of those &#x1f937;&#x200d;&#x2642;&#xfe0f;.</p>



<p>For sure, we will also use the async approach here as well, cause we don&#8217;t want laggs here as well. But first, start a new project over here as well. Pick the WPF App Visual Studio template and choose NET 6 as well. Now we will do the basic MVVM setup stuff, where I won&#8217;t go into too much detail &#8211; I will cover this in detail in a future post.</p>



<h3 class="wp-block-heading">The WPF UI</h3>



<p>Go ahead and install my favourite WPF NuGet helper libraries:</p>



<ul class="wp-block-list">
<li>Autofac &#8211; Managing dependency injections, IoC, etc.</li>



<li>Caliburn.Micro &#8211; Easier WPF work by naming conventions</li>



<li>MahApps.Metro &#8211; One of my favourite Design Toolkits</li>



<li>PropertyChanged.Fody &#8211; Get rid of annoying NotifyPropertyChanged implementations</li>
</ul>



<p>After you&#8217;ve installed the recommended libraries (or prefer to go without them), continue with installing the most important package. I&#8217;m talking about the used bluetooth <strong><a href="#Creating-a-new-project-installing-the-32feet-lib">lib from above</a></strong>.</p>



<p>Then create the basic MVVM folders (if used) inside your project folder like this:</p>



<ul class="wp-block-list">
<li>Converters</li>



<li>ViewModels</li>



<li>Views</li>
</ul>



<h3 class="wp-block-heading">Necessary imports inside App.xaml</h3>



<p>After that we can continue by importing the necessary styles and other things inside the &#8222;App.xaml&#8220; file. As we are not using the default boot-process in my case, take care of that removed Start-Uri thingy from at the top.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="xml" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">&lt;Application x:Class="BluetoothExampleWpfDeviceSearch.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:local="clr-namespace:BluetoothExampleWpfDeviceSearch"
             xmlns:mah="http://metro.mahapps.com/winfx/xaml/controls"
             xmlns:c="clr-namespace:BluetoothExampleWpfDeviceSearch.Converters">
    &lt;Application.Resources>
        &lt;ResourceDictionary>
            &lt;ResourceDictionary.MergedDictionaries>
                &lt;ResourceDictionary>
                    &lt;local:Bootstrapper x:Key="bootstrapper" />
                    &lt;c:RectConverter x:Key="RectConverter" />
                &lt;/ResourceDictionary>
                &lt;ResourceDictionary>
                    &lt;ResourceDictionary.MergedDictionaries>
                        &lt;!-- MahApps.Metro resource dictionaries. Make sure that all file names are Case Sensitive! -->
                        &lt;ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Controls.xaml" />
                        &lt;ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Fonts.xaml" />
                        &lt;!-- Theme setting -->
                        &lt;ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Themes/Light.Orange.xaml" />
                    &lt;/ResourceDictionary.MergedDictionaries>
                &lt;/ResourceDictionary>
            &lt;/ResourceDictionary.MergedDictionaries>
        &lt;/ResourceDictionary>
    &lt;/Application.Resources>
&lt;/Application>
</pre>



<h3 class="wp-block-heading">Bootstrapping the App</h3>



<p>Next we will create 2 classes being able to actually bootstrap our app. The first one is the base, which provides essential base functionality. Don&#8217;t worry if you don&#8217;t understand everything there, just read it carefully and learn step by step – for this example just take this note: It&#8217;s a generic bootstrapping base for our app.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="csharp" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">using System.Linq;
using Autofac;
using Caliburn.Micro;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows;
using IContainer = Autofac.IContainer;
using BluetoothExampleWpfDeviceSearch.ViewModels;

namespace BluetoothExampleWpfDeviceSearch;

public abstract class TypedAutofacBootstrapper&lt;TRootViewModel> : BootstrapperBase
{
    public static IContainer? Container { get; private set; }

    protected IEventAggregator? _eventAggregator { get; private set; }

    public TypedAutofacBootstrapper()
    {
        Initialize();
    }

    #region Overrides
    protected override void Configure()
    {
        var builder = new ContainerBuilder();

        RegisterBasicUtilities(builder);
        RegisterViewModels(builder);
        RegisterViews(builder);

        ConfigureContainer(builder);

        Container = builder.Build();
    }

    protected void RegisterBasicUtilities(ContainerBuilder builder)
    {
        builder.RegisterType&lt;WindowManager>()
            .As&lt;IWindowManager>()
            .SingleInstance();

        _eventAggregator = new EventAggregator();
        builder.RegisterInstance(_eventAggregator)
            .As&lt;IEventAggregator>()
            .SingleInstance();
    }

    protected static Func&lt;Type, bool> mustEndWithViewModelButNotShellViewModel = type => type.Name.EndsWith("ViewModel") &amp;&amp; type.Name != "ShellViewModel";
    protected static Func&lt;Type, bool> mustBeInNamespaceEndingOnViewModels = type => !string.IsNullOrWhiteSpace(type.Namespace) &amp;&amp; type.Namespace.EndsWith("ViewModels");
    protected static Func&lt;Type, bool> mustImplementPropertyChanged = type => type.GetInterface(nameof(INotifyPropertyChanged)) != null;

    protected void RegisterViewModels(ContainerBuilder builder)
    {
        var assembly = AssemblySource.Instance;
        builder.RegisterAssemblyTypes(assembly.ToArray())
          .Where(type => type.Name == nameof(ShellViewModel))
          .AsSelf()
          .SingleInstance();
        //.PropertiesAutowired();
        builder.RegisterAssemblyTypes(assembly.ToArray())
          .Where(mustEndWithViewModelButNotShellViewModel)
          .Where(mustBeInNamespaceEndingOnViewModels)
          .Where(mustImplementPropertyChanged)
          .AsSelf()
          .InstancePerDependency();
        //.PropertiesAutowired();
    }

    protected static Func&lt;Type, bool> mustEndWithView = type => type.Name.EndsWith("View");
    protected static Func&lt;Type, bool> mustBeInNamespaceEndingOnViews = type => !string.IsNullOrWhiteSpace(type.Namespace) &amp;&amp; type.Namespace.EndsWith("Views");

    protected void RegisterViews(ContainerBuilder builder)
    {
        var assembly = AssemblySource.Instance;
        builder.RegisterAssemblyTypes(assembly.ToArray())
          .Where(mustEndWithView)
          .Where(mustBeInNamespaceEndingOnViews)
          .AsSelf()
          .InstancePerDependency()
          .PropertiesAutowired();
    }

    protected override object GetInstance(Type serviceType, string key)
    {
        if (string.IsNullOrWhiteSpace(key))
        {
            if (Container.IsRegistered(serviceType))
                return Container.Resolve(serviceType);
        }
        else
        {
            if (Container.IsRegisteredWithKey(key, serviceType))
                return Container.ResolveKeyed(key, serviceType);
        }
        throw new Exception($"Could not locate any instances of contract {key ?? serviceType.Name}.");
    }

    protected override IEnumerable&lt;object> GetAllInstances(Type serviceType)
    {
        var ienumerableType = typeof(IEnumerable&lt;>);
        var genericServiceEnumerableType = ienumerableType.MakeGenericType(serviceType);
        return Container.Resolve(genericServiceEnumerableType) as IEnumerable&lt;object>;
    }

    protected override void BuildUp(object instance)
    {
        // Debug.WriteLine("BuildUp");
        Container.InjectProperties(instance);
    }
    #endregion

    protected override async void OnStartup(object sender, StartupEventArgs e)
    {
        base.OnStartup(sender, e);
        await DisplayRootViewForAsync&lt;TRootViewModel>();
        ApplicationStarted();
    }

    protected abstract void ApplicationStarted();

    protected abstract void ConfigureContainer(ContainerBuilder builder);
}</pre>



<p>Now we will create the actual implementation of the previous class – our app specific bootstrapper. The you will see, that this class it&#8217;s much less code. It will just start the App window (which comes next) and provides the (base) &#8222;ShellViewModel&#8220; instance.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="csharp" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">using Autofac;
using Caliburn.Micro;
using BluetoothExampleWpfDeviceSearch.ViewModels;
using System.Linq;
using IContainer = Autofac.IContainer;

namespace BluetoothExampleWpfDeviceSearch;

public class Bootstrapper : TypedAutofacBootstrapper&lt;ShellViewModel>
{

    protected override void ConfigureContainer(ContainerBuilder builder)
    {
        // register more stuff specific to your app
    }

    protected override void ApplicationStarted()
    {

    }

}</pre>



<h3 class="wp-block-heading">Creating the ShellViewModel</h3>



<p>The &#8222;ShellViewModel&#8220; is the basic shell around our app, you could say, it&#8217;s the &#8222;window&#8220;. Go ahead and create it inside the &#8222;ViewModels&#8220; folder. In modern applications, there are likely less windows being used. You basically switch out sub-views of the main app and only use windows if appropriate. So right now we&#8217;re only saying: When the app is started, show our start screen, which is basically a &#8222;CallViewModel&#8220;. Sorry for the name, took it out of the old project.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="csharp" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">using Autofac;
using Caliburn.Micro;

namespace BluetoothExampleWpfDeviceSearch.ViewModels;

public class ShellViewModel : Conductor&lt;IScreen>.Collection.OneActive
{

    public ShellViewModel()
    {
        ShowStartScreen();
    }

    private async void ShowStartScreen()
    {
        var callViewModel = Bootstrapper.Container.Resolve&lt;CallViewModel>();
        await ActivateItemAsync(callViewModel);
    }
}
</pre>



<p>Now we need the corresponding view as well, the &#8222;ShellView&#8220;, which should be created inside the &#8222;Views&#8220; folder (you may delete the MainWindow file previously!). I won&#8217;t go into Caliburn Micro, etc. here, because the post maybe is long enough right now haha. Basically we&#8217;re showing the current view (which is called ActiveItem) by naming convention based databinding.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="xml" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">&lt;mah:MetroWindow x:Class="BluetoothExampleWpfDeviceSearch.Views.ShellView"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:mah="http://metro.mahapps.com/winfx/xaml/controls"
        mc:Ignorable="d"
        d:DesignWidth="1366"
        d:DesignHeight="720"
        Title="BluetoothExampleWpfDeviceSearch" BorderThickness="0" GlowBrush="Black" AllowsTransparency="True" Name="TheWindow" IsWindowDraggable="True" SizeToContent="WidthAndHeight" WindowStartupLocation="CenterScreen">

    &lt;mah:MetroWindow.Clip>
        &lt;RectangleGeometry RadiusX="8" RadiusY="8">
            &lt;RectangleGeometry.Rect>
                &lt;MultiBinding Converter="{StaticResource RectConverter}">
                    &lt;Binding ElementName="TheWindow" Path="ActualWidth"/>
                    &lt;Binding ElementName="TheWindow" Path="ActualHeight"/>
                &lt;/MultiBinding>
            &lt;/RectangleGeometry.Rect>
        &lt;/RectangleGeometry>
    &lt;/mah:MetroWindow.Clip>

    &lt;mah:TransitioningContentControl Name="ActiveItem" />

&lt;/mah:MetroWindow>
</pre>



<h2 class="wp-block-heading">The list page ViewModel</h2>



<p>In this step, we will create the actual view for listing our devices. Create a new viewmodel called &#8222;CallViewModel&#8220; (or correct it and directly name it BluetoothDeviceListViewModel).</p>



<p>We basically have a storage list, where we keep our found devices – notice the &#8222;BindableCollection&#8220; type. This type comes from &#8222;Caliburn.Micro&#8220; and helps us – seeing the name – with binding to a collection. Maybe a separate post will be coming for this, too, for now it&#8217;s enough to know.</p>



<p>Then we are keeping track of which device is actually selected with the &#8222;SelectedDevice&#8220; property. And we are also remembering, if we are currently busy searching for devices. This will ensure, that the button isn&#8217;t usable, if we are already searching.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="csharp" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">using Caliburn.Micro;
using InTheHand.Net.Bluetooth;
using InTheHand.Net.Sockets;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BluetoothExampleWpfDeviceSearch.ViewModels;

public class CallViewModel : Screen
{

    public BindableCollection&lt;DeviceItemViewModel> Devices { get; set; }

    public DeviceItemViewModel? SelectedDevice { get; set; }

    public bool IsSearchingDevices { get; set; }

    public CallViewModel()
    {
        Devices = new();
        IsSearchingDevices = false;
    }

    public async Task SearchDevices()
    {
        IsSearchingDevices = true;
        Devices.Clear();
        var client = new BluetoothClient();
        var devices = new List&lt;BluetoothDeviceInfo>();
        try
        {
            devices.AddRange((await Task.Run(() => client.DiscoverDevices())).ToList());
        }
        catch (Exception ex)
        {
            Debug.WriteLine(ex.Message);
        }
        finally
        {
            Devices.AddRange(devices.Select(x => new DeviceItemViewModel(x)));
            client.Close();
            IsSearchingDevices = false;
        }
    }

    public bool CanSearchDevices => !IsSearchingDevices;

}</pre>



<h3 class="wp-block-heading">The list page View</h3>



<p>Now add another UserControl inside the Views folder and call it &#8222;CallView&#8220; (or use the corrected version like BluetoothDeviceListView). Here we are also using some of caliburns helper conventions. I&#8217;m just telling the &#8222;ListBox&#8220;: &#8222;Hey, your name is &#8218;Devices&#8216;, so, bind to those&#8220; &#8211; and it just works.</p>



<p>Then i&#8217;m defining a template for the items to be displayed. This could also be a separate file and the line I&#8217;ve commented out. Like this, caliburn would automatically look for a file fitting the naming style &#8222;DeviceItemViewModel&#8220; -&gt; &#8222;DeviceItemView&#8220; whose ViewModel we are going to create now.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="xml" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">&lt;UserControl x:Class="BluetoothExampleWpfDeviceSearch.Views.CallView"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             xmlns:local="clr-namespace:BluetoothExampleWpfDeviceSearch.Views"
             mc:Ignorable="d" 
             Height="380" Width="700" Margin="64">
    &lt;Grid>
        &lt;StackPanel Width="300" HorizontalAlignment="Center" VerticalAlignment="Center">
            &lt;GroupBox Header="Devices" Margin="0 12" MinHeight="150">
                &lt;!-- Using default template-->
                &lt;!--&lt;ListBox Name="Devices" />-->
                
                &lt;!-- Using custom template (without caliburn convention..) -->
                &lt;ListBox Name="Devices">
                    &lt;ListBox.ItemTemplate>
                        &lt;DataTemplate>
                            &lt;StackPanel>
                                &lt;TextBlock Text="{Binding Device.DeviceName}" FontSize="15" FontWeight="Bold" Margin="0 8 0 0" />
                                &lt;TextBlock Text="{Binding Device.DeviceAddress}" FontSize="13" Margin="0 0 0 8" />
                                &lt;Border BorderThickness="0 1 0 0" BorderBrush="Black" />
                            &lt;/StackPanel>
                        &lt;/DataTemplate>
                    &lt;/ListBox.ItemTemplate>
                &lt;/ListBox>
            &lt;/GroupBox>
            &lt;Button Name="SearchDevices" Content="Scan for Bluetooth devices" />
        &lt;/StackPanel>
    &lt;/Grid>
&lt;/UserControl>
</pre>



<h3 class="wp-block-heading">The device item ViewModel &#8211; the last step</h3>



<p>In the last step, we will create a simple ViewModel to hold the device for us:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="csharp" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">using Caliburn.Micro;
using InTheHand.Net.Sockets;

namespace BluetoothExampleWpfDeviceSearch.ViewModels;

public class DeviceItemViewModel : PropertyChangedBase
{

    public BluetoothDeviceInfo Device { get; }

    public DeviceItemViewModel(BluetoothDeviceInfo device)
    {
        Device = device;
    }

}
</pre>



<h2 class="wp-block-heading">Conclusion – C# Bluetooth example</h2>



<p>So in todays post we learned how to use the 32feet bluetooth library, to list / search for bluetooth devices. We covered a complete Windows Forms example and also a WPF MVVM app example of implementing the explained functionality. I hope this will get your bluetooth aware app on fire – cheers!</p>



<h2 class="wp-block-heading">Downloads</h2>



<div class="wp-block-buttons is-layout-flex wp-block-buttons-is-layout-flex">
<div class="wp-block-button"><a class="wp-block-button__link wp-element-button" href="https://bit.ly/csharp-bluetooth-example-list-download-hp" target="_blank" rel="noreferrer noopener">Winforms-Example</a></div>



<div class="wp-block-button"><a class="wp-block-button__link wp-element-button" href="https://bit.ly/csharp-bluetooth-example-list-download-wpf-hp" target="_blank" rel="noreferrer noopener">WPF-Example</a></div>
</div>



<h2 class="wp-block-heading">Related posts</h2>



<ul class="wp-block-list">
<li><strong><a href="https://robbelroot.de/blog/hacking-a-net-application/" target="_blank" rel="noreferrer noopener">Hacking a .NET Application</a></strong></li>



<li><strong><a href="https://robbelroot.de/blog/hacking-a-webshop/" target="_blank" rel="noreferrer noopener">Webshop hacking – don&#8217;t fall for this common trap</a></strong></li>



<li><strong><a href="https://robbelroot.de/blog/converting-davinci-resolve-markers-to-youtube-chapters/" target="_blank" rel="noreferrer noopener">Converting Davinci resolve markers to YouTube chapters</a></strong></li>
</ul>
<p>Der Beitrag <a href="https://robbelroot.de/blog/csharp-bluetooth-example-searching-listing-devices/">C# Bluetooth example – searching &#038; listing devices in 2024</a> erschien zuerst auf <a href="https://robbelroot.de">Robert Skibbe</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://robbelroot.de/blog/csharp-bluetooth-example-searching-listing-devices/feed/</wfw:commentRss>
			<slash:comments>12</slash:comments>
		
		
			</item>
		<item>
		<title>Excel Kalenderwoche</title>
		<link>https://robbelroot.de/blog/excel-kalenderwoche/</link>
					<comments>https://robbelroot.de/blog/excel-kalenderwoche/#comments</comments>
		
		<dc:creator><![CDATA[Robert Skibbe]]></dc:creator>
		<pubDate>Thu, 12 Aug 2021 19:01:11 +0000</pubDate>
				<category><![CDATA[Allgemein]]></category>
		<category><![CDATA[Excel]]></category>
		<category><![CDATA[Excel Problemlösungen]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[büro]]></category>
		<category><![CDATA[calendar]]></category>
		<category><![CDATA[daten]]></category>
		<category><![CDATA[datum]]></category>
		<category><![CDATA[excel]]></category>
		<category><![CDATA[jahr]]></category>
		<category><![CDATA[kalender]]></category>
		<category><![CDATA[kalenderwoche]]></category>
		<category><![CDATA[microsoft]]></category>
		<category><![CDATA[monat]]></category>
		<category><![CDATA[msft]]></category>
		<category><![CDATA[office]]></category>
		<category><![CDATA[planen]]></category>
		<category><![CDATA[planung]]></category>
		<category><![CDATA[produkt]]></category>
		<category><![CDATA[produkte]]></category>
		<category><![CDATA[projekt]]></category>
		<category><![CDATA[projektplanung]]></category>
		<category><![CDATA[range]]></category>
		<category><![CDATA[reichweite]]></category>
		<category><![CDATA[reihe]]></category>
		<category><![CDATA[software]]></category>
		<category><![CDATA[spalte]]></category>
		<category><![CDATA[tag]]></category>
		<category><![CDATA[vba]]></category>
		<category><![CDATA[week]]></category>
		<category><![CDATA[woche]]></category>
		<guid isPermaLink="false">https://robbelroot.de/?p=5266</guid>

					<description><![CDATA[<p>Excel Kalenderwoche Du möchtest eine Excel Kalenderwoche bestimmen, um zum Beispiel diverse Projekte wie einen Kalender, o. Ä. umzusetzen? Dann begrüße ich Dich herzlich in meinem heutigen Beitrag über die Kalenderwoche, bzw. die Kalenderwochen-Funktion in Excel! Vielleicht helfen Dir später auch noch weitere Beiträge zum Thema Microsoft Excel, wie Diese &#8230;</p>
<p>Der Beitrag <a href="https://robbelroot.de/blog/excel-kalenderwoche/">Excel Kalenderwoche</a> erschien zuerst auf <a href="https://robbelroot.de">Robert Skibbe</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<figure class="wp-block-image size-large"><a href="https://robbelroot.de/wp-content/uploads/2021/08/Excel-Kalenderwoche.png"><img loading="lazy" decoding="async" width="1024" height="536" src="https://robbelroot.de/wp-content/uploads/2021/08/Excel-Kalenderwoche-1024x536.png" alt="Excel Kalenderwoche" class="wp-image-5271" title="Excel Kalenderwoche" srcset="https://robbelroot.de/wp-content/uploads/2021/08/Excel-Kalenderwoche-1024x536.png 1024w, https://robbelroot.de/wp-content/uploads/2021/08/Excel-Kalenderwoche-300x157.png 300w, https://robbelroot.de/wp-content/uploads/2021/08/Excel-Kalenderwoche-768x402.png 768w, https://robbelroot.de/wp-content/uploads/2021/08/Excel-Kalenderwoche-700x366.png 700w, https://robbelroot.de/wp-content/uploads/2021/08/Excel-Kalenderwoche-332x174.png 332w, https://robbelroot.de/wp-content/uploads/2021/08/Excel-Kalenderwoche.png 1200w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></a><figcaption>Excel Kalenderwoche</figcaption></figure>






<h2 class="wp-block-heading">Excel Kalenderwoche</h2>



<p>Du <strong>möchtest </strong>eine <strong>Excel Kalenderwoche</strong> bestimmen, <strong>um </strong>zum Beispiel diverse <strong>Projekte wie </strong>einen <strong>Kalender</strong>, o. Ä. umzusetzen?</p>



<p><strong>Dann </strong>begrüße ich Dich herzlich in meinem <strong>heutigen Beitrag über </strong>die <strong>Kalenderwoche</strong>, bzw. die Kalenderwochen-Funktion in <strong>Excel</strong>!</p>



<p><strong>Vielleicht </strong>helfen Dir <strong>später </strong>auch <strong>noch </strong>weitere <strong>Beiträge </strong>zum Thema <strong>Microsoft Excel</strong>, wie Diese hier: <strong><a href="https://robbelroot.de/blog/excel-makro-erstellen/" target="_blank" rel="noreferrer noopener">VBA Makro</a></strong>, <strong><a href="https://robbelroot.de/blog/vba-range/" target="_blank" rel="noreferrer noopener">Range</a></strong>, <strong><a href="https://robbelroot.de/blog/ifs-vba/">IFS VBA</a></strong>.</p>



<h2 class="wp-block-heading">Kalenderwochen – Häufig gebraucht</h2>



<p>Ich denke <strong>absolut jeder</strong>, <strong>der </strong>mal <strong>mit Daten </strong>(plural Datum) <strong>gearbeitet </strong>hat, ist früher oder später an ein und dasselbe <strong>Problem </strong>geraten – <strong>Kalenderwochen</strong>.</p>



<p>Diese <strong>Problemstellung </strong>ist wie viele Andere auch, <strong>nicht plattformabhängig</strong>, da z. B. <strong>Kalender </strong>nun einmal <strong>auf verschiedenen Plattformen gebraucht </strong>werden.</p>



<p>Was jedoch <strong>Plattform</strong>&#8211; <strong>und </strong>auch <strong>kontextual</strong>&#8211;<strong>abhängig </strong>ist, <strong>sind </strong>deren jeweilige <strong>Umsetzungen auf </strong>den entsprechenden <strong>Plattformen</strong>.</p>



<h2 class="wp-block-heading">Google-Kalender – Ein Beispiel</h2>



<p><strong>Neben </strong>Microsoft <strong>Outlook </strong>verwenden natürlich <strong>auch andere </strong>bekannte <strong>Anbieter wie </strong>z. B. <strong>Google </strong>die Darstellung von <strong>Kalenderwochen</strong>.</p>



<p><strong>Bei Outlook </strong>muss man Diese <strong>teilweise </strong>(also je nach Version und Einstellungen) allerdings erst <strong>aktivieren</strong>.</p>



<p><strong>Auf </strong>dem <strong>Handy </strong>sehe ich <strong>aktuell </strong>auch in der Monatsansicht z. B. <strong>keine Kalenderwochen </strong>(ich nutze aktuell ein <strong>iPhone </strong>XR mit dem <strong>iOS-Kalender</strong>).</p>



<figure class="wp-block-image size-large"><a href="https://robbelroot.de/wp-content/uploads/2021/08/Kalenderwochen-im-Google-Kalender.png"><img loading="lazy" decoding="async" width="1024" height="718" src="https://robbelroot.de/wp-content/uploads/2021/08/Kalenderwochen-im-Google-Kalender-1024x718.png" alt="Kalenderwochen im Google Kalender" class="wp-image-5290" title="Kalenderwochen im Google Kalender" srcset="https://robbelroot.de/wp-content/uploads/2021/08/Kalenderwochen-im-Google-Kalender-1024x718.png 1024w, https://robbelroot.de/wp-content/uploads/2021/08/Kalenderwochen-im-Google-Kalender-300x210.png 300w, https://robbelroot.de/wp-content/uploads/2021/08/Kalenderwochen-im-Google-Kalender-768x538.png 768w, https://robbelroot.de/wp-content/uploads/2021/08/Kalenderwochen-im-Google-Kalender-700x490.png 700w, https://robbelroot.de/wp-content/uploads/2021/08/Kalenderwochen-im-Google-Kalender-332x233.png 332w, https://robbelroot.de/wp-content/uploads/2021/08/Kalenderwochen-im-Google-Kalender.png 1303w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></a><figcaption>Kalenderwochen im Google Kalender</figcaption></figure>



<h2 class="wp-block-heading">Excel Kalenderwoche, etwa berechnen?</h2>



<p>Im <strong>Internet </strong>finden sich für die <strong>verschiedensten Sprachen </strong>und <strong>Plattformen Codeschnippsel</strong>, <strong>wie </strong>man die <strong>Kalenderwoche </strong>eines gegebenen Datum <strong>berechnen </strong>kann.</p>



<p>Wie man <strong>Kalenderwochen</strong> errechnet, bzw. bestimmt ist ja <strong>mehr oder weniger </strong>ein <strong>offenes </strong>Geheimnis, denn wie fast alles im Leben, <strong>gibt es </strong>auch <strong>hierfür Normen</strong>.</p>



<p>Unter anderem gibt es die <strong>für uns eher interessante</strong> <strong><a href="https://de.wikipedia.org/wiki/Woche#Z%C3%A4hlweise_nach_ISO_8601" target="_blank" rel="noreferrer noopener">Norm &#8222;ISO8601&#8220;</a></strong> und die z. B. in den <strong><a href="https://de.wikipedia.org/wiki/Woche#Berechnung_in_den_USA_und_vielen_anderen_L%C3%A4ndern" target="_blank" rel="noreferrer noopener">USA vertretene Norm</a></strong>.</p>



<p><strong>Zum Glück </strong>gibt es aber zumindest <strong>einige Hilfsmittel</strong>, Welche es uns <strong>ermöglichen</strong>, <strong>auf </strong>vorhandene <strong>Tools zurückzugreifen</strong>, <strong>statt </strong>alles in <strong>Eigenarbeit </strong>zu berechnen.</p>



<p>Das <strong>sieht </strong>dann je <strong>nach Programmier</strong>&#8211; und <strong>Skriptsprache </strong>ggf. <strong>anders </strong>aus und ist <strong>mal mehr </strong>und mal <strong>weniger </strong>kompliziert.</p>



<p>Hier siehst Du beispielsweise ein <strong>ISO8601</strong>&#8211;<strong>Beispiel aus </strong>dem <strong>VB.NET-Umfeld</strong>:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="visualbasic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">Public Shared Function GetIso8601WeekOfYear(time As DateTime) As Integer
    Dim day As DayOfWeek = CultureInfo.InvariantCulture.Calendar.GetDayOfWeek(time)

    If day >= DayOfWeek.Monday AndAlso day &lt;= DayOfWeek.Wednesday Then
        time = time.AddDays(3)
    End If

    Return CultureInfo.InvariantCulture.Calendar.GetWeekOfYear(time, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday)
End Function</pre>



<h2 class="wp-block-heading">Durch Verwendung von VBA-Code</h2>



<p>Wer <strong>im Bereich Excel </strong>unterwegs ist, wird vermutlich auch irgendwann in Kontakt mit <strong>Microsofts Skriptsprache Visual Basic for Applications</strong> (kurz VBA) kommen.</p>



<p><strong>Auch dort </strong>könnte eventuell die <strong>Notwendigkeit </strong>für die Erörterung der <strong>Kalenderwoche eines </strong>bestimmten <strong>Datums </strong>vorkommen.</p>



<p>In <strong>VBA </strong>selbst gibt es dazu eine relativ <strong>einfache Funktion</strong>, Welche sich in der <strong>Dokumentation </strong>unter dem <strong>Namen </strong>&#8222;<strong><a href="https://docs.microsoft.com/de-de/office/vba/api/excel.worksheetfunction.weeknum" target="_blank" rel="noreferrer noopener">WeekNum</a></strong>&#8220; versteckt.</p>



<p>Ein möglicher <strong>Beispielcode </strong>dazu könnte <strong>so </strong>aussehen:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="visualbasic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">Dim weekNumber As Integer = WorksheetFunction.WeekNum(now, vbMonday)
' do something with weekNumber..</pre>



<h2 class="wp-block-heading">Gerade und ungerade Kalenderwochen</h2>



<p><strong>Eventuell </strong>besteht ja auch die <strong>Notwendigkeit</strong> zum Beispiel in &#8222;<strong>geraden Kalenderwochen</strong>&#8220; <strong>anders </strong>zu verfahren, <strong>als </strong>in <strong>Ungeraden</strong>.</p>



<p><strong>Womöglich </strong>möchte man die <strong>Reihen</strong>, oder <strong>Spalten </strong>anders <strong>färben</strong>, oder die <strong>Werte </strong>innerhalb der Zellen <strong>anders verarbeiten</strong>.</p>



<p>Dies <strong>könnte </strong>man z. B. <strong>wie folgt </strong>lösen:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="visualbasic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">Dim weekNumber As Integer = WorksheetFunction.WeekNum(now, vbMonday)
Dim isWeekNumberEven As Boolean = weekNumber Mod 2
If isWeekNumberEven Then
    ' do something on even weeknumber..
Else
    ' do something on odd weeknumber
End If</pre>



<h2 class="wp-block-heading">Excel Kalenderwoche – Einfachste Methode</h2>



<p>Ganz nach dem &#8222;das <strong>Beste </strong>kommt <strong>zum Schluss</strong>&#8222;-Motto, gibt es <strong>in Excel </strong>wohl (zum Glück) eine <strong>sehr einfache Variante</strong>, um an die <strong>Kalenderwoche </strong>zu kommen.</p>



<p>Dazu verwendet man die <strong>gleichermaßen benannte Methode </strong>namens <strong><a href="https://support.microsoft.com/de-de/office/kalenderwoche-funktion-e5c43a03-b4ab-426c-b411-b18c13c75340" target="_blank" rel="noreferrer noopener">KALENDERWOCHE</a></strong> – einfach, oder!?</p>



<p>Dessen genauen <strong>Aufbau mit Parametern </strong>und<strong> Details</strong>, kannst Du Dir in der oben verlinkten <strong>Seite der Dokumentation </strong>anschauen.</p>



<p><strong>Achte </strong>bei dem folgenden Code-Beispiel <strong>besonders auf </strong>den <strong>zweiten Parameter</strong>, Dieser gibt eine <strong>wichtige Information </strong>an.</p>



<p>Der <strong>zweite Parameter </strong>der Funktion <strong>bestimmt </strong>dabei, an <strong>welchem Wochentag </strong>die <strong>Woche</strong>(n) für die Berechnung <strong>starten </strong>soll.</p>



<p>Beim <strong>ersten Parameter </strong>hingegen handelt es sich um den <strong>jeweiligen Wert </strong>(also <strong>das Datum</strong>), Welcher verwendet werden soll.</p>



<p>Dabei <strong>handelt </strong>es <strong>sich </strong>im unteren Beispiel natürlich um den <strong>Wert in </strong>der <strong>Zelle </strong>&#8222;<strong>A2</strong>&#8222;.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">=KALENDERWOCHE(A2;2)</pre>
<p>Der Beitrag <a href="https://robbelroot.de/blog/excel-kalenderwoche/">Excel Kalenderwoche</a> erschien zuerst auf <a href="https://robbelroot.de">Robert Skibbe</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://robbelroot.de/blog/excel-kalenderwoche/feed/</wfw:commentRss>
			<slash:comments>3</slash:comments>
		
		
			</item>
		<item>
		<title>VBA Range</title>
		<link>https://robbelroot.de/blog/vba-range/</link>
					<comments>https://robbelroot.de/blog/vba-range/#comments</comments>
		
		<dc:creator><![CDATA[Robert Skibbe]]></dc:creator>
		<pubDate>Sun, 18 Jul 2021 18:34:35 +0000</pubDate>
				<category><![CDATA[Allgemein]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[Visual Basic for Applications]]></category>
		<category><![CDATA[Visual Basic for Applications Problemlösungen]]></category>
		<category><![CDATA[application]]></category>
		<category><![CDATA[applications]]></category>
		<category><![CDATA[basic]]></category>
		<category><![CDATA[bereich]]></category>
		<category><![CDATA[calculation]]></category>
		<category><![CDATA[excel]]></category>
		<category><![CDATA[excel vba]]></category>
		<category><![CDATA[for]]></category>
		<category><![CDATA[kalkulation]]></category>
		<category><![CDATA[kalkulieren]]></category>
		<category><![CDATA[range]]></category>
		<category><![CDATA[reichweite]]></category>
		<category><![CDATA[tabelle]]></category>
		<category><![CDATA[tabellen]]></category>
		<category><![CDATA[tables]]></category>
		<category><![CDATA[vb]]></category>
		<category><![CDATA[vba]]></category>
		<category><![CDATA[visual]]></category>
		<category><![CDATA[visual basic]]></category>
		<category><![CDATA[zeile]]></category>
		<category><![CDATA[zelle]]></category>
		<category><![CDATA[zellen]]></category>
		<guid isPermaLink="false">https://robbelroot.de/?p=4449</guid>

					<description><![CDATA[<p>VBA Range Du möchtest mit der VBA Range und somit mit einen ganzen Bereich in Excel arbeiten? Lerne in diesem Beitrag, wie Du mit der VBA Range Funktion ganze Bereiche erfassen und verarbeiten kannst. Vielleicht interessieren Dich zu einem anderen Zeitpunkt noch folgende Beiträge: VBA InStr, Array, Array Length. Was &#8230;</p>
<p>Der Beitrag <a href="https://robbelroot.de/blog/vba-range/">VBA Range</a> erschien zuerst auf <a href="https://robbelroot.de">Robert Skibbe</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<figure class="wp-block-image size-large"><a href="https://robbelroot.de/wp-content/uploads/2021/07/VBA-Range.png"><img loading="lazy" decoding="async" width="1024" height="536" src="https://robbelroot.de/wp-content/uploads/2021/07/VBA-Range-1024x536.png" alt="VBA Range" class="wp-image-4451" title="VBA Range" srcset="https://robbelroot.de/wp-content/uploads/2021/07/VBA-Range-1024x536.png 1024w, https://robbelroot.de/wp-content/uploads/2021/07/VBA-Range-300x157.png 300w, https://robbelroot.de/wp-content/uploads/2021/07/VBA-Range-768x402.png 768w, https://robbelroot.de/wp-content/uploads/2021/07/VBA-Range-700x366.png 700w, https://robbelroot.de/wp-content/uploads/2021/07/VBA-Range-332x174.png 332w, https://robbelroot.de/wp-content/uploads/2021/07/VBA-Range.png 1200w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></a><figcaption>VBA Range</figcaption></figure>






<h2 class="wp-block-heading">VBA Range</h2>



<p>Du <strong>möchtest </strong>mit der <strong>VBA Range</strong> und <strong>somit </strong>mit einen ganzen Bereich in <strong>Excel </strong>arbeiten?</p>



<p><strong>Lerne </strong>in diesem Beitrag, <strong>wie </strong>Du mit der <strong>VBA Range Funktion</strong> ganze <strong>Bereiche erfassen </strong>und <strong>verarbeiten </strong>kannst.</p>



<p><strong>Vielleicht interessieren </strong>Dich zu einem <strong>anderen Zeitpunkt </strong>noch <strong>folgende Beiträge</strong>: <strong><a href="/blog/vba-instr" target="_blank" rel="noreferrer noopener">VBA InStr</a></strong>, <strong><a href="/blog/excel-vb-array" target="_blank" rel="noreferrer noopener">Array</a></strong>, <strong><a href="/blog/array-length-vb" target="_blank" rel="noreferrer noopener">Array Length</a></strong>.</p>



<h2 class="wp-block-heading">Was ist eine VBA Range</h2>



<p>Eine <strong>Range </strong>in <strong>VBA</strong>, bzw. in <strong><a href="https://www.microsoft.com/de-de/microsoft-365/excel" target="_blank" rel="noreferrer noopener">Microsoft Excel</a></strong>, ist – übersetzt gesehen – eine <strong>Reichweite </strong>von mehreren <strong>Zellen </strong>einer <strong>Tabelle</strong>.</p>



<p><strong>Wie Du </strong>Dir sicher <strong>vorstellen </strong>kannst, können wir so <strong>diverse Zeilen </strong>und <strong>Spalten </strong>abbilden und letztendlich durchlaufen.</p>



<p><strong>Damit </strong>können wir unter anderem <strong>Summierungen</strong>, oder andere <strong>eigene Arbeitsschritte </strong>anwenden.</p>



<h2 class="wp-block-heading">Die Qual der Wahl</h2>



<p>Naja ganz so schlimm ist es nicht &#x1f602;, jedoch gibt es <strong>2 tolle Auswahlmöglichkeiten </strong>für die <strong>Ranges</strong>.</p>



<p>Die <strong>erste Möglichkeit </strong>auf die <strong>VBA Ranges</strong> zuzugreifen ist es, den <strong>User </strong>ganz <strong>einfach </strong>wie bekannt seine <strong>eigene Auswahl treffen </strong>zu <strong>lassen </strong>und dann im Code <strong>auf </strong>die <strong>Auswahl zuzugreifen</strong>.</p>



<p>Bei der <strong>zweiten Möglichkeit </strong>handelt es sich mehr oder weniger um eine <strong>manuelle</strong> Methode, wo wir – wie <strong>aus Excel bekannt </strong>– die <strong>Ranges mit </strong>ich nenne es mal &#8222;<strong>Selektoren</strong>&#8220; <strong>bestimmen</strong>.</p>



<h2 class="wp-block-heading">Manuelle Auswahl des Nutzers – VBA Range</h2>



<p><strong>Stell </strong>Dir <strong>vor</strong>, der <strong>Nutzer </strong>deiner Anwendung <strong>markiert </strong>die <strong>Zellen </strong>z. B. wie folgt:</p>



<figure class="wp-block-image size-large"><a href="https://robbelroot.de/wp-content/uploads/2021/07/VBA-Range-Excel-Beispiel-Auswahl.png"><img loading="lazy" decoding="async" width="553" height="138" src="https://robbelroot.de/wp-content/uploads/2021/07/VBA-Range-Excel-Beispiel-Auswahl.png" alt="VBA Range Excel Beispiel Auswahl" class="wp-image-4464" title="VBA Range Excel Beispiel Auswahl" srcset="https://robbelroot.de/wp-content/uploads/2021/07/VBA-Range-Excel-Beispiel-Auswahl.png 553w, https://robbelroot.de/wp-content/uploads/2021/07/VBA-Range-Excel-Beispiel-Auswahl-300x75.png 300w, https://robbelroot.de/wp-content/uploads/2021/07/VBA-Range-Excel-Beispiel-Auswahl-332x83.png 332w" sizes="auto, (max-width: 553px) 100vw, 553px" /></a><figcaption>VBA Range Excel Beispiel Auswahl</figcaption></figure>



<p><strong>Er hat </strong>also praktisch die &#8222;Koordinaten&#8220; <strong>A1, A2 und A3</strong> in dieser <strong>Tabelle</strong>, bzw. diesem Tabellenblatt <strong>markiert</strong>.</p>



<p><strong>Anders formuliert</strong>, <strong>könnte </strong>man diese &#8222;Range&#8220; auch in &#8222;<strong>Excel-Sprache</strong>&#8220; ausdrücken, <strong>was </strong>dann <strong>als </strong>&#8222;A1:A3&#8220; <strong>bezeichnet </strong>werden würde.</p>



<p>Diese <strong>Range können </strong>wir im Grunde <strong>genauso in </strong>unserem <strong>VBA </strong>Skript <strong>verwenden</strong>, <strong>um </strong>die z. B. die Daten aus den respektiven <strong>Zellen </strong>abzurufen.</p>



<h2 class="wp-block-heading">Auswahl via Code – VBA Range</h2>



<p>Doch <strong>bevor </strong>wir <strong>mit </strong>dem <strong>tatsächlichen Abrufen </strong>von Werten, bzw. <strong>Iterieren </strong>von <strong>Zellen beginnen</strong>, <strong>werfen </strong>wir nochmal einen <strong>Blick auf </strong>die Auswahl der <strong>Range </strong>via Code.</p>



<p>Wie <strong>oben </strong>schon <strong>angesprochen </strong>verwenden wir dafür einen <strong>Ausdruck</strong>, Welchen ich als <strong>Selektor </strong>bezeichne und <strong>übergeben </strong>Diesen der <strong>Range-Funktion </strong>aus Excel.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="visualbasic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">Dim area
area = Range("A1:A3")</pre>



<p>Im <strong>Code deklarieren </strong>wir dazu erstmal eine <strong>Variable </strong>namens &#8222;area&#8220; <strong>und weisen </strong>Ihr anschließend den <strong>Rückgabewert der Range</strong>&#8211;<strong>Funktion </strong>zu.</p>



<p><strong>Danach </strong>haben wir endlich die <strong>Möglichkeit</strong>, die einzelnen Zellen, <strong>Welche </strong>hier durch die <strong>Range widergespiegelt </strong>werden zu <strong>durchlaufen</strong>.</p>



<h2 class="wp-block-heading">Zellen der Range durchlaufen</h2>



<p>Um durch die <strong>einzelnen Zellen </strong>der Range zu iterieren <strong>nutzen </strong>wir im folgenden Beispiel die &#8222;<strong>For Each</strong>&#8222;-<strong>Schleife</strong>:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="visualbasic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">For Each cell in area
    ' do something
Next</pre>



<p><strong>Nun </strong>können wir <strong>innerhalb </strong>der einzelnen Schleifen-<strong>Durchläufe </strong>auf die jeweilige Zelle zugreifen.</p>



<p>Wir haben dadurch die <strong>Möglichkeit </strong>einerseits die <strong>hinter </strong>den <strong>Zellen </strong>steckenden <strong>Werte abgreifen </strong>und setzen, sowie die <strong>Formeln </strong>der Zellen <strong>verändern</strong>.</p>



<h2 class="wp-block-heading">Werte der Zellen abrufen und verändern</h2>



<p><strong>Hier </strong>zeige ich Dir, wie Du einzelne <strong>Werte aus </strong>den <strong>Zellen abrufen und setzen </strong>kannst:</p>



<h3 class="wp-block-heading">Werte abrufen</h3>



<pre class="EnlighterJSRAW" data-enlighter-language="visualbasic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">For Each cell in area
    Dim value = cell.Value
    ' so something with the value
Next</pre>



<h3 class="wp-block-heading">Werte setzen</h3>



<pre class="EnlighterJSRAW" data-enlighter-language="visualbasic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">For Each cell in area
    cell.Value = "The new Value!"
Next</pre>



<h2 class="wp-block-heading">Mit Formeln arbeiten</h2>



<p>Im <strong>nächsten Abschnitt </strong>kümmern wir uns um das <strong>Setzen und Abrufen </strong>der Formeln.</p>



<h3 class="wp-block-heading">Formel setzen</h3>



<p>Wir haben die <strong>Möglichkeit </strong>die <strong>Formeln </strong>einer <strong>Range </strong>direkt zu setzen:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="visualbasic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">Range("A1:A3").Formula = "=Rand()"</pre>



<p>Oder <strong>wie </strong>im obigen Beispiel <strong>mit </strong>Hilfe einer <strong>Schleife</strong>:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="visualbasic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">For Each cell in area
    cell.Formula = "=Rand()"
Next</pre>
<p>Der Beitrag <a href="https://robbelroot.de/blog/vba-range/">VBA Range</a> erschien zuerst auf <a href="https://robbelroot.de">Robert Skibbe</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://robbelroot.de/blog/vba-range/feed/</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
			</item>
	</channel>
</rss>
